<?php
/**
 * @Copyright Copyright (C) 2009-2010 ... Webit Solution
 * @license GNU/GPL http://www.gnu.org/copyleft/gpl.html
 * Company:		Webit Solution
 + Contact:		www.webits.asia, info@webits.asia
 * Created on:	Mar 21, 2012
 ^
 + Project: 		Job Posting and Employment Application
 * File Name:	admin-----/models/wrecruit.php
 ^ 
 * Description: Model for application on admin site
 ^ 
 * History:		NONE
 ^ 
 */

defined('_JEXEC') or die('Restricted access');
jimport('joomla.application.component.model');
jimport('joomla.html.html');


class WRecruitModelWRecruit extends JModel
{
	var $_id;
	var $_application;
	var $_options;
	var $_empoptions;
	var $_uid;
	var $_job = null;
	var $_config = null;
	var $_defaultcountry = null;
	var $_job_editor = null;
	var $_comp_editor = null;
	var $_data_directory = null;
	var $_shifts = null;
    var $_jobsalaryrange = null;
    var $_experiences = null;
    var $_ages = null;
    var $_careerlevels = null;
    var $_searchoptions = null;
	var $_defaultcurrency = null;
	function __construct()
	{
		parent :: __construct();

                /*
		$cid = JRequest :: getVar('cid', false, 'DEFAULT', 'array');
		if ($cid) $id = $cid[0];
		else $id = JRequest :: getInt('id', 0);
		$this->setId($id);
                 *
                 */
	}
// Search Start
	function getAllCompaniesForSearch( $title )
	{
			$db =& JFactory::getDBO();
			$query = "SELECT id, name FROM ".$db->nameQuote('#__wrecruit_companies')." ORDER BY name ASC ";
			$db->setQuery( $query );
			$rows = $db->loadObjectList();
			if ($db->getErrorNum()) {
				echo $db->stderr();
				return false;
			}
			$companies = array();
			if($title)
				$companies[] =  array('value' => JText::_(''),'text' => $title);
			foreach($rows as $row){
				$companies[] =  array('value' => $row->id,'text' => $row->name);
			}
		return $companies;
	}

	function &getJobSearch($keyword,$jobcategory,$jobtype,$jobstatus,$salaryrangefrom,$salaryrangeto,$salaryrangetype
							,$shift,  $durration, $startpublishing, $stoppublishing
							,$company,$country,$state,$county,$city,$zipcode,$limit,$limitstart)
	{
		if ($jobcategory != '') if (is_numeric($jobcategory) == false) return false;
		if ($jobtype != '') if (is_numeric($jobtype) == false) return false;
		if ($jobstatus != '') if (is_numeric($jobstatus) == false) return false;
		//if ($jobsalaryrange != '') if (is_numeric($jobsalaryrange) == false) return false;
                if ($salaryrangefrom != '')if (is_numeric($salaryrangefrom) == false) return false;
                if ($salaryrangeto != '')if (is_numeric($salaryrangeto) == false) return false;
                if ($salaryrangetype != '')if (is_numeric($salaryrangetype) == false) return false;
		if ($shift != '') if (is_numeric($shift) == false) return false;
		if ($company != '') if (is_numeric($company) == false) return false;
		//if ($currency != '')if (is_numeric($currency) == false) return false;
		$result = array();
		$db = &$this->getDBO();


		if(! isset($this->_config)){
			$this->getConfig('');
		}
		foreach ($this->_config as $conf){
				if ($conf->configname == 'date_format') $dateformat = $conf->configvalue;
		}
		if ($startpublishing != ''){
			if($dateformat == 'm-d-Y'){
				$arr = explode('-', $startpublishing);
				$startpublishing =  $arr[2].'-'.$arr[0].'-'.$arr[1];
			}elseif($dateformat == 'd-m-Y'){
				$arr = explode('-', $startpublishing);
				$startpublishing =  $arr[2].'-'.$arr[1].'-'.$arr[0];
			}
		 	$startpublishing =  date('Y-m-d',strtotime($startpublishing));
		 }
		if ($stoppublishing != ''){
			if($dateformat == 'm-d-Y'){
				$arr = explode('-', $stoppublishing);
				$stoppublishing =  $arr[2].'-'.$arr[0].'-'.$arr[1];
			}elseif($dateformat == 'd-m-Y'){
				$arr = explode('-', $stoppublishing);
				$stoppublishing =  $arr[2].'-'.$arr[1].'-'.$arr[0];
			}
			$stoppublishing =  date('Y-m-d',strtotime($stoppublishing));
		}
		$listjobconfig = $this->getConfigByFor('listjob');
		$issalary = '';

		$wherequery = '';
		if ($keyword != '') $wherequery .= " AND (job.title LIKE '%".str_replace("'","",$db->Quote($keyword))."%' OR" .
											" job.description LIKE '%".str_replace("'","",$db->Quote($keyword))."%')";
		if ($jobcategory != '') $wherequery .= " AND job.jobcategory = ".$jobcategory;
		if ($jobtype != '') $wherequery .= " AND job.jobtype = ".$jobtype;
		if ($jobstatus != '') $wherequery .= " AND job.jobstatus = ".$jobstatus;
		if ($salaryrangefrom != ''){
			$salaryrangefromJoin = " 
                                        JOIN ".$db->nameQuote('#__wrecruit_salaryrange')." AS salaryrangef ON salaryrangef.id = ".$salaryrangefrom;
			$wherequery .= " AND salaryrangefrom.rangestart >= salaryrangef.rangestart ";
			$issalary = 1;
		}
		if ($salaryrangeto != ''){
			$salaryrangetoJoin = " 
					JOIN ".$db->nameQuote('#__wrecruit_salaryrange')." AS salaryranget ON salaryranget.id = ".$salaryrangeto;
			$wherequery .= " AND salaryrangeto.rangeend <= salaryranget.rangeend ";
			$issalary = 1;
		}
		if (($issalary != '') && ($salaryrangetype != '')){
			$wherequery .= " AND job.salaryrangetype = ".$salaryrangetype;
		}
		if ($shift != '') $wherequery .= " AND job.shift = ".$shift;
		//if ($experience != '') $wherequery .= " AND job.experience LIKE ".$db->Quote($experience);
		if ($durration != '') $wherequery .= " AND job.duration LIKE ".$db->Quote($durration);
		if ($startpublishing != '') $wherequery .= " AND job.startpublishing >= ".$db->Quote($startpublishing);
		if ($stoppublishing != '') $wherequery .= " AND job.stoppublishing <= ".$db->Quote($stoppublishing);
		if ($company != '') $wherequery .= " AND job.companyid = ".$company;
		if ($country != '') $wherequery .= " AND job.country = country.code AND country.code LIKE ".$db->Quote($country);
		//if ($state != '') $wherequery .= " AND job.state = state.code AND (state.code = ".$db->Quote($state)." OR LOWER(state.name) LIKE ".$db->Quote( '%'.$db->getEscaped( $state, true ).'%', false )." ) ";
		if ($state != '') $wherequery .= " AND (LOWER(job.state) LIKE ".$db->Quote( '%'.$db->getEscaped( $state, true ).'%', false )." ) ";
		//if ($county != '') $wherequery .= " AND job.county = county.code AND (county.code = ".$db->Quote($county)." OR LOWER(county.name) LIKE ".$db->Quote( '%'.$db->getEscaped( $county, true ).'%', false )." ) ";
		if ($county != '') $wherequery .= " AND (LOWER(job.county) LIKE ".$db->Quote( '%'.$db->getEscaped( $county, true ).'%', false )." ) ";
		//if ($city != '') $wherequery .= " AND job.city = city.code AND (city.code = ".$db->Quote($city)." OR LOWER(city.name) LIKE ".$db->Quote( '%'.$db->getEscaped( $city, true ).'%', false )." ) ";
		if ($city != '') $wherequery .= " AND  (LOWER(job.city) LIKE ".$db->Quote( '%'.$db->getEscaped( $city, true ).'%', false )." ) ";
//		if ($county != '') $wherequery .= " AND county.name LIKE ".$db->Quote($county);
//		if ($city != '') $wherequery .= " AND city.name LIKE ".$db->Quote($city);
		if ($zipcode != '') $wherequery .= " AND job.zipcode = ".$db->Quote($zipcode);

		$curdate = date('Y-m-d H:i:s');
		$query = "SELECT count(job.id) FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job 
					JOIN ".$db->nameQuote('#__wrecruit_categories')." AS cat ON job.jobcategory = cat.id
					LEFT JOIN ".$db->nameQuote('#__wrecruit_salaryrange')." AS salaryrangefrom ON job.salaryrangefrom = salaryrangefrom.id
					LEFT JOIN ".$db->nameQuote('#__wrecruit_salaryrange')." AS salaryrangeto ON job.salaryrangeto = salaryrangeto.id";
                        if ($salaryrangefrom != '') $query .= $salaryrangefromJoin;
                        if ($salaryrangeto != '') $query .= $salaryrangetoJoin;
                        $query .= " , ".$db->nameQuote('#__wrecruit_categories')." AS cat ";
			if ($country != '') $query .= " LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS country ON job.country = country.code ";
			if ($state != '') $query .= " LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS state ON job.state = state.code ";
			if ($county != '') $query .= " LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS county ON job.county = county.code ";
			if ($city != '') $query .= " LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS city ON job.city = city.code ";
			//if ($currency != '') $query .= " LEFT JOIN ".$db->nameQuote('#__wrecruit_currencies')." AS currency ON curency.id = job.currencyid ";
			$query .= " LEFT JOIN ".$db->nameQuote('#__wrecruit_currencies')." AS currency ON curency.id = job.currencyid ";
			$query .= "	WHERE job.status = 1
				AND job.startpublishing <= " . $db->Quote($curdate) . " AND job.stoppublishing >= " . $db->Quote($curdate);
		$query .= $wherequery;
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$total = $db->loadResult();
		if ( $total <= $limitstart ) $limitstart = 0;

		$query = "SELECT job.*, cat.cat_title, jobtype.title AS jobtypetitle, jobstatus.title AS jobstatustitle
				, salaryrangefrom.rangestart AS salaryfrom, salaryrangeto.rangeend AS salaryend, country.name AS countryname
				, company.name AS companyname, company.url
				FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job
				JOIN ".$db->nameQuote('#__wrecruit_categories')." AS cat ON job.jobcategory = cat.id
				JOIN ".$db->nameQuote('#__wrecruit_jobtypes')." AS jobtype ON job.jobtype = jobtype.id
				JOIN ".$db->nameQuote('#__wrecruit_jobstatus')." AS jobstatus ON job.jobstatus = jobstatus.id
				LEFT JOIN ".$db->nameQuote('#__wrecruit_companies')." AS company ON job.companyid = company.id
				LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS country ON job.country = country.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_salaryrange')." AS salaryrangefrom ON job.salaryrangefrom = salaryrangefrom.id
				LEFT JOIN ".$db->nameQuote('#__wrecruit_salaryrange')." AS salaryrangeto ON job.salaryrangeto = salaryrangeto.id";
                                if ($salaryrangefrom != '') $query .= $salaryrangefromJoin;
                                if ($salaryrangeto != '') $query .= $salaryrangetoJoin;
			if ($state != '') $query .= " LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS state ON job.state = state.code ";
			if ($county != '') $query .= " LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS county ON job.county = county.code ";
			if ($city != '') $query .= " LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS city ON job.city = city.code ";
			//if ($currency != '') $query .= " LEFT JOIN ".$db->nameQuote('#__wrecruit_currencies')." AS currency ON currency.id = job.currencyid ";
			$query .= " LEFT JOIN ".$db->nameQuote('#__wrecruit_currencies')." AS currency ON currency.id = job.currencyid ";
			$query .= " WHERE  job.status = 1 
						AND job.startpublishing <= " . $db->Quote($curdate) . " AND job.stoppublishing >= " . $db->Quote($curdate);
			//if ($currency != '') $query.= " AND currency.id = job.currencyid ";
			$query.= " AND currency.id = job.currencyid ";

		$query .= $wherequery;
		//echo '<br> SQL '.$query;
		//$db->setQuery($query);
		$db->setQuery($query, $limitstart, $limit);
		$this->_applications = $db->loadObjectList();

		$result[0] = $this->_applications;
		$result[1] = $total;
		$result[2]=$listjobconfig;

		return $result;
	}

	function &getSearchOptions()
	{
		$searchjobconfig = $this->getConfigByFor('searchjob');

		if ( !$this->_searchoptions )
		{
			$this->_searchoptions = array();

			$companies = $this->getAllCompaniesForSearch(JText::_('JS_SEARCH_ALL'));
			$job_type = $this->getJobType(JText::_('JS_SEARCH_ALL'));
			$jobstatus = $this->getJobStatus(JText::_('JS_SEARCH_ALL'));
			$heighesteducation = $this->getHeighestEducation(JText::_('JS_SEARCH_ALL'));
			$job_categories = $this->getCategories(JText::_('JS_SEARCH_ALL'),'');
			$job_salaryrange = $this->getJobSalaryRange(JText::_('JS_SEARCH_ALL'),'');
			$shift = $this->getShift(JText::_('JS_SEARCH_ALL'));
			$countries = $this->getCountries('');

			if(! isset($this->_config)){ $this->getConfig();}
			if(isset($this->_defaultcountry))$states = $this->getStates($this->_defaultcountry);
			$this->_searchoptions['country'] = JHTML::_('select.genericList', $countries, 'country','class="inputbox required" '.'onChange="dochange(\'state\', this.value)"', 'value', 'text', $this->_defaultcountry);
			if ( isset($states[1]) ) if ($states[1] != '')$this->_searchoptions['state'] = JHTML::_('select.genericList', $states, 'state', 'class="inputbox" '. 'onChange="dochange(\'county\', this.value)"', 'value', 'text', '');
			if ( isset($counties[1]) ) if ($counties[1] != '')$this->_searchoptions['county'] = JHTML::_('select.genericList', $counties, 'county', 'class="inputbox" '. 'onChange="dochange(\'city\', this.value)"', 'value', 'text', '');
			if ( isset($cities[1]) ) if ($cities[1] != '')$this->_searchoptions['city'] = JHTML::_('select.genericList', $cities, 'city', 'class="inputbox" '. '', 'value', 'text', '');
			$this->_searchoptions['companies'] = JHTML::_('select.genericList', $companies, 'company', 'class="inputbox" '. '', 'value', 'text', '');
			$this->_searchoptions['jobcategory'] = JHTML::_('select.genericList', $job_categories, 'jobcategory', 'class="inputbox" '. '', 'value', 'text', '');
			//$this->_searchoptions['jobsalaryrange'] = JHTML::_('select.genericList', $job_salaryrange, 'jobsalaryrange', 'class="inputbox" '. '', 'value', 'text', '');
			$this->_searchoptions['jobsalaryrange'] = JHTML::_('select.genericList', $job_salaryrange, 'jobsalaryrange', 'class="inputbox" '. '', 'value', 'text', '');
			$this->_searchoptions['salaryrangefrom'] = JHTML::_('select.genericList', $this->getSalaryRange(JText::_('JS_FROM')), 'salaryrangefrom', 'class="inputbox" '. '', 'value', 'text', '');
			$this->_searchoptions['salaryrangeto'] = JHTML::_('select.genericList', $this->getSalaryRange(JText::_('JS_TO')), 'salaryrangeto', 'class="inputbox" '. '', 'value', 'text', '');
			$this->_searchoptions['salaryrangetypes'] = JHTML::_('select.genericList', $this->getSalaryRangeTypes(''), 'salaryrangetype', 'class="inputbox" '. '', 'value', 'text', 2);
			$this->_searchoptions['jobstatus'] = JHTML::_('select.genericList', $jobstatus, 'jobstatus', 'class="inputbox" '. '', 'value', 'text', '');
			$this->_searchoptions['jobtype'] = JHTML::_('select.genericList', $job_type, 'jobtype', 'class="inputbox" '. '', 'value', 'text', '');
			$this->_searchoptions['heighestfinisheducation'] = JHTML::_('select.genericList', $heighesteducation, 'heighestfinisheducation', 'class="inputbox" '. '', 'value', 'text', '');
			$this->_searchoptions['shift'] = JHTML::_('select.genericList', $shift, 'shift', 'class="inputbox" '. '', 'value', 'text', '');
			$this->_searchoptions['currency'] = JHTML::_('select.genericList', $this->getCurrency(), 'currency', 'class="inputbox" '. '', 'value', 'text', '');
		}
		$result = array();
		$result[0] = $this->_searchoptions;
		$result[1] = $searchjobconfig;
		return $result;
	}
	function &getResumeSearch($uid,$title,$name,$nationality,$gender,$iamavailable,$jobcategory,$jobtype,$jobstatus,$jobsalaryrange,$education
								, $experience,$limit,$limitstart,$currency)
	{
		if ($gender != '')  if (is_numeric($gender) == false) return false;
		if ($iamavailable != '')  if (is_numeric($iamavailable) == false) return false;
		if ($jobcategory != '')  if (is_numeric($jobcategory) == false) return false;
		if ($jobtype != '')  if (is_numeric($jobtype) == false) return false;
		if ($jobsalaryrange != '')  if (is_numeric($jobsalaryrange) == false) return false;
		if ($education != '')  if (is_numeric($education) == false) return false;

		if ($currency != '')  if (is_numeric($currency) == false) return false;
		$db = &$this->getDBO();



		$result = array();
		$searchresumeconfig = $this->getConfigByFor('searchresume');

		$wherequery = '';
		if ($title != '') $wherequery .= " AND resume.application_title LIKE '%".str_replace("'","",$db->Quote($title))."%'";
		if ($name!= '') {
			$wherequery .= " AND (";
				$wherequery .= " LOWER(resume.first_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $name, true ).'%', false );
				$wherequery .= " OR LOWER(resume.last_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $name, true ).'%', false );
				$wherequery .= " OR LOWER(resume.middle_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $name, true ).'%', false );
			$wherequery .= " )";
		}

		if ($nationality != '') $wherequery .= " AND resume.nationality = ".$db->Quote($nationality);
		if ($gender != '') $wherequery .= " AND resume.gender = ".$gender;
		if ($iamavailable != '') $wherequery .= " AND resume.iamavailable = ".$iamavailable;
		if ($jobcategory != '') $wherequery .= " AND resume.job_category = ".$jobcategory;
		if ($jobtype != '') $wherequery .= " AND resume.jobtype = ".$jobtype;
		if ($jobsalaryrange != '') $wherequery .= " AND resume.jobsalaryrange = ".$jobsalaryrange;
		if ($education != '') $wherequery .= " AND resume.heighestfinisheducation = ".$education;
		if ($experience != '') $wherequery .= " AND resume.total_experience LIKE ".$db->Quote($experience);

		$query = "SELECT count(resume.id) FROM ".$db->nameQuote('#__wrecruit_resume')." AS resume, ".$db->nameQuote('#__wrecruit_categories')." AS cat
				WHERE resume.job_category = cat.id AND resume.status = 1 AND resume.searchable = 1  ";
		$query .= $wherequery;
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$total = $db->loadResult();

		if ( $total <= $limitstart ) $limitstart = 0;
		$query = "SELECT resume.*, cat.cat_title, jobtype.title AS jobtypetitle
				, salary.rangestart, salary.rangeend , currency.symbol
				FROM ".$db->nameQuote('#__wrecruit_resume')." AS resume
				JOIN ".$db->nameQuote('#__wrecruit_jobtypes')." AS jobtype ON resume.jobtype = jobtype.id
				LEFT JOIN ".$db->nameQuote('#__wrecruit_currencies')." AS currency ON currency.id = resume.currencyid 	AND currency.id =  " .$currency." 		
				LEFT JOIN ".$db->nameQuote('#__wrecruit_salaryrange')." AS salary ON resume.jobsalaryrange = salary.id
				, ".$db->nameQuote('#__wrecruit_categories')." AS cat ";
			$query .= "WHERE resume.job_category = cat.id AND resume.status = 1 AND resume.searchable = 1";
		$query .= $wherequery;

		//echo '<br> SQL '.$query;

		$db->setQuery($query, $limitstart, $limit);


		$result[0] = $db->loadObjectList();
		$result[1] = $total;
		$result[2] = $searchresumeconfig;

		return $result;
	}
	function &getResumeSearchOptions()
	{

			$db = &$this->getDBO();

			$searchresumeconfig = $this->getConfigByFor('searchresume');

			$gender = array(
			'0' => array('value' => '','text' => JText::_('JS_SEARCH_ALL')),
			'1' => array('value' => 1,'text' => JText::_('JS_MALE')),
			'2' => array('value' => 2,'text' => JText::_('JS_FEMALE')),);

			$nationality = $this->getCountries(JText::_('JS_SEARCH_ALL'));
			$job_type = $this->getJobType(JText::_('JS_SEARCH_ALL'));
			$heighesteducation = $this->getHeighestEducation(JText::_('JS_SEARCH_ALL'));
			$job_categories = $this->getCategories(JText::_('JS_SEARCH_ALL'),'');
			$job_salaryrange = $this->getJobSalaryRange(JText::_('JS_SEARCH_ALL'),'');

			$searchoptions['nationality'] = JHTML::_('select.genericList', $nationality, 'nationality', 'class="inputbox" '. '', 'value', 'text', '');
			$searchoptions['jobcategory'] = JHTML::_('select.genericList', $job_categories, 'jobcategory', 'class="inputbox" '. '', 'value', 'text', '');
			$searchoptions['jobsalaryrange'] = JHTML::_('select.genericList', $job_salaryrange, 'jobsalaryrange', 'class="inputbox" '. '', 'value', 'text', '');
			$searchoptions['jobtype'] = JHTML::_('select.genericList', $job_type, 'jobtype', 'class="inputbox" '. '', 'value', 'text', '');
			$searchoptions['heighestfinisheducation'] = JHTML::_('select.genericList', $heighesteducation, 'heighestfinisheducation', 'class="inputbox" '. '', 'value', 'text', '');
			$searchoptions['gender'] = JHTML::_('select.genericList', $gender, 'gender', 'class="inputbox" '. '', 'value', 'text', '');
			$searchoptions['currency'] = JHTML::_('select.genericList', $this->getCurrency(), 'currency', 'class="inputbox" '. '', 'value', 'text', '');
			$result=array();
			$result[0]=$searchoptions;
			$result[1]=$searchresumeconfig;

			return $result;
	}

// Search End


// Get By ID Start
	function &getJobbyIdForView($job_id)
	{
		$db = &$this->getDBO();
		if (is_numeric($job_id) == false) return false;

		$query = "SELECT job.*, cat.cat_title , company.name as companyname, jobtype.title AS jobtypetitle
				, jobstatus.title AS jobstatustitle, shift.title as shifttitle
				, department.name AS departmentname
				, salaryfrom.rangestart AS salaryfrom, salaryto.rangestart AS salaryto, salarytype.title AS salarytype
				, education.title AS educationtitle ,mineducation.title AS mineducationtitle, maxeducation.title AS maxeducationtitle
				, experience.title AS experiencetitle ,minexperience.title AS minexperiencetitle, maxexperience.title AS maxexperiencetitle
				, country.name AS countryname, state.name AS statename, county.name AS countyname, city.name AS cityname
		FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job
		JOIN ".$db->nameQuote('#__wrecruit_categories')." AS cat ON job.jobcategory = cat.id
		JOIN ".$db->nameQuote('#__wrecruit_companies')." AS company ON job.companyid = company.id
		JOIN ".$db->nameQuote('#__wrecruit_jobtypes')." AS jobtype ON job.jobtype = jobtype.id
		JOIN ".$db->nameQuote('#__wrecruit_jobstatus')." AS jobstatus ON job.jobstatus = jobstatus.id
		LEFT JOIN ".$db->nameQuote('#__wrecruit_departments')." AS department ON job.departmentid = department.id
		LEFT JOIN ".$db->nameQuote('#__wrecruit_salaryrange')." AS salaryfrom ON job.salaryrangefrom = salaryfrom.id
		LEFT JOIN ".$db->nameQuote('#__wrecruit_salaryrange')." AS salaryto ON job.salaryrangeto = salaryto.id
		LEFT JOIN ".$db->nameQuote('#__wrecruit_salaryrangetypes')." AS salarytype ON job.salaryrangetype = salarytype.id
		LEFT JOIN ".$db->nameQuote('#__wrecruit_heighesteducation')." AS education ON job.educationid = education.id
		LEFT JOIN ".$db->nameQuote('#__wrecruit_heighesteducation')." AS mineducation ON job.mineducationrange = mineducation.id
		LEFT JOIN ".$db->nameQuote('#__wrecruit_heighesteducation')." AS maxeducation ON job.maxeducationrange = maxeducation.id
		LEFT JOIN ".$db->nameQuote('#__wrecruit_experiences')." AS experience ON job.experienceid = experience.id
		LEFT JOIN ".$db->nameQuote('#__wrecruit_experiences')." AS minexperience ON job.minexperiencerange = minexperience.id
		LEFT JOIN ".$db->nameQuote('#__wrecruit_experiences')." AS maxexperience ON job.maxexperiencerange = maxexperience.id
		LEFT JOIN ".$db->nameQuote('#__wrecruit_shifts')." AS shift ON job.shift = shift.id
		LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS country ON job.country = country.code
		LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS state ON job.state = state.code
		LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS county ON job.county = county.code
		LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS city ON job.city = city.code
		WHERE  job.id = " . $job_id;
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$this->_application = $db->loadObject();



		$result[0] = $this->_application;
		//$result[2] = $this->getUserFieldsForView(2, $job_id); // company fields, id
		$result[3] = $this->getFieldsOrderingforForm(2); // company fields

		return $result;
	}

	function &getCompanybyIdForView($companyid)
	{
		$db = &$this->getDBO();
		if (is_numeric($companyid) == false) return false;
		$query = "SELECT company.*, cat.cat_title, country.name AS countryname, state.name AS statename
					, county.name AS countyname, city.name AS cityname
		FROM ".$db->nameQuote('#__wrecruit_companies')." AS company
		JOIN ".$db->nameQuote('#__wrecruit_categories')." AS cat ON company.category = cat.id
		LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS country ON company.country = country.code
		LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS state ON company.state = state.code
		LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS county ON company.county = county.code
		LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS city ON company.city = city.code
		WHERE  company.id = " . $companyid;
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$result[0] = $db->loadObject();
		$result[3] = $this->getFieldsOrderingforForm(1);
		return $result;
	}

	function & getDepartmentById($c_id,$uid)
	{
		if($uid) if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		if (is_numeric($c_id) == false) return false;
		$db = & JFactory :: getDBO();
		$result = array();

		$query = "SELECT department.*
		FROM ".$db->nameQuote('#__wrecruit_departments')." AS department
		 WHERE department.id=".$c_id;
		//echo $query;
		$db->setQuery($query,$limitstart, $limit);
		$department = $db->loadObject();
		$companies = $this->getCompanies($uid);
		if ( isset($department) ){
			$lists['companies'] = JHTML::_('select.genericList', $companies, 'companyid', 'class="inputbox required" '. '', 'value', 'text', $department->companyid);

		}else{
			$lists['companies'] = JHTML::_('select.genericList', $companies, 'companyid', 'class="inputbox required" '. '', 'value', 'text', '');
                }


		$result[0] = $department;
		$result[1] = $lists;
		return $result;
	}
	function &getResumeViewbyId($id)
	{
		if (is_numeric($id) == false) return false;
		$db = &$this->getDBO();
                $status = array(
                '0' => array('value' => 0,'text' => JText::_('JS_PENDDING')),
                '1' => array('value' => 1,'text' => JText::_('JS_APPROVE')),
                '2' => array('value' => -1,'text' => JText::_('JS_REJECT')),);
                $lists['status'] = JHTML::_('select.genericList', $status, 'status', 'class="inputbox required" '. '', 'value', 'text', $message->status);
		$query = "SELECT app.* , cat.cat_title AS categorytitle, salary.rangestart, salary.rangeend, jobtype.title AS jobtypetitle
				,heighesteducation.title AS heighesteducationtitle
				, nationality_country.name AS nationalitycountry
				, address_city.name AS address_city2 , address_county.name AS address_county2 , address_state.name AS address_state2 , address_country.name AS address_country
				, address1_city.name AS address1_city2 , address1_county.name AS address1_county2 , address1_state.name AS address1_state2 , address1_country.name AS address1_country
				, address2_city.name AS address2_city2 , address2_county.name AS address2_county2 , address2_state.name AS address2_state2 , address2_country.name AS address2_country
				, currency.symbol as symbol	


				FROM ".$db->nameQuote('#__wrecruit_resume')." AS app
				JOIN ".$db->nameQuote('#__wrecruit_categories')." AS cat ON app.job_category = cat.id
				JOIN ".$db->nameQuote('#__wrecruit_jobtypes')." AS jobtype ON app.jobtype = jobtype.id
				LEFT JOIN ".$db->nameQuote('#__wrecruit_heighesteducation')." AS heighesteducation ON app.heighestfinisheducation = heighesteducation.id
				LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS nationality_country ON app.nationality = nationality_country.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_salaryrange')." AS salary ON app.jobsalaryrange = salary.id
				LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS address_city ON app.address_city = address_city.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS address_county ON app.address_county = address_county.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS address_state ON app.address_state = address_state.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS address_country ON app.address_country = address_country.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS address1_city ON app.address1_city = address1_city.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS address1_county ON app.address1_county = address1_county.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS address1_state ON app.address1_state = address1_state.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS address1_country ON app.address1_country = address1_country.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS address2_city ON app.address2_city = address2_city.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS address2_county ON app.address2_county = address2_county.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS address2_state ON app.address2_state = address2_state.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS address2_country ON app.address2_country = address2_country.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_currencies')." AS currency ON currency.id = app.currencyid

				WHERE app.id = ". $id ;
		//echo '<br> sql '.$query;
		$query2 = "SELECT app.id

				, institute_city.name AS institute_city2 , institute_county.name AS institute_county2 , institute_state.name AS institute_state2 , institute_country.name AS institute_country
				, institute1_city.name AS institute1_city2 , institute1_county.name AS institute1_county2 , institute1_state.name AS institute1_state2 , institute1_country.name AS institute1_country
				, institute2_city.name AS institute2_city2 , institute2_county.name AS institute2_county2 , institute2_state.name AS institute2_state2 , institute2_country.name AS institute2_country
				, institute3_city.name AS institute3_city2 , institute3_county.name AS institute3_county2 , institute3_state.name AS institute3_state2 , institute3_country.name AS institute3_country

				, employer_city.name AS employer_city2 , employer_county.name AS employer_county2 , employer_state.name AS employer_state2 , employer_country.name AS employer_country
				, employer1_city.name AS employer1_city2 , employer1_county.name AS employer1_county2 , employer1_state.name AS employer1_state2 , employer1_country.name AS employer1_country
				, employer2_city.name AS employer2_city2 , employer2_county.name AS employer2_county2 , employer2_state.name AS employer2_state2 , employer2_country.name AS employer2_country
				, employer3_city.name AS employer3_city2 , employer3_county.name AS employer3_county2 , employer3_state.name AS employer3_state2 , employer3_country.name AS employer3_country

				FROM ".$db->nameQuote('#__wrecruit_resume')." AS app

				LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS institute_city ON app.institute_city = institute_city.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS institute_county ON app.institute_county = institute_county.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS institute_state ON app.institute_state = institute_state.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS institute_country ON app.institute_country = institute_country.code

				LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS institute1_city ON app.institute1_city = institute1_city.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS institute1_county ON app.institute1_county = institute1_county.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS institute1_state ON app.institute1_state = institute1_state.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS institute1_country ON app.institute1_country = institute1_country.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS institute2_city ON app.institute2_city = institute2_city.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS institute2_county ON app.institute2_county = institute2_county.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS institute2_state ON app.institute2_state = institute2_state.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS institute2_country ON app.institute2_country = institute2_country.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS institute3_city ON app.institute3_city = institute3_city.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS institute3_county ON app.institute3_county = institute3_county.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS institute3_state ON app.institute3_state = institute3_state.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS institute3_country ON app.institute3_country = institute3_country.code


				LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS employer_city ON app.employer_city = employer_city.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS employer_county ON app.employer_county = employer_county.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS employer_state ON app.employer_state = employer_state.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS employer_country ON app.employer_country = employer_country.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS employer1_city ON app.employer1_city = employer1_city.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS employer1_county ON app.employer1_county = employer1_county.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS employer1_state ON app.employer1_state = employer1_state.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS employer1_country ON app.employer1_country = employer1_country.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS employer2_city ON app.employer2_city = employer2_city.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS employer2_county ON app.employer2_county = employer2_county.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS employer2_state ON app.employer2_state = employer2_state.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS employer2_country ON app.employer2_country = employer2_country.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS employer3_city ON app.employer3_city = employer3_city.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS employer3_county ON app.employer3_county = employer3_county.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS employer3_state ON app.employer3_state = employer3_state.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS employer3_country ON app.employer3_country = employer3_country.code

				WHERE app.id = ". $id ;

		$db->setQuery( 'SET SQL_BIG_SELECTS=1');
		$db->query();

		$db->setQuery($query);
		$resume = $db->loadObject();

		$db->setQuery($query2);
		$resume2 = $db->loadObject();



		$result[0] = $resume;
		$result[1] = $resume2;
		$result[2] = $this->getResumeViewbyId3($id);
		$result[3] = $this->getFieldsOrderingforForm(3); // resume fields
		$result[4] = $lists;
		return $result;
	}

	function &getResumeViewbyId3($id)
	{
		if (is_numeric($id) == false) return false;
		$db = &$this->getDBO();
		$query = "SELECT app.id

				, reference_city.name AS reference_city2 , reference_county.name AS reference_county2 , reference_state.name AS reference_state2 , reference_country.name AS reference_country
				, reference1_city.name AS reference1_city2 , reference1_county.name AS reference1_county2 , reference1_state.name AS reference1_state2 , reference1_country.name AS reference1_country
				, reference2_city.name AS reference2_city2 , reference2_county.name AS reference2_county2 , reference2_state.name AS reference2_state2 , reference2_country.name AS reference2_country
				, reference3_city.name AS reference3_city2 , reference3_county.name AS reference3_county2 , reference3_state.name AS reference3_state2 , reference3_country.name AS reference3_country

				FROM ".$db->nameQuote('#__wrecruit_resume')." AS app



				LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS reference_city ON app.reference_city = reference_city.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS reference_county ON app.reference_county = reference_county.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS reference_state ON app.reference_state = reference_state.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS reference_country ON app.reference_country = reference_country.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS reference1_city ON app.reference1_city = reference1_city.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS reference1_county ON app.reference1_county = reference1_county.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS reference1_state ON app.reference1_state = reference1_state.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS reference1_country ON app.reference1_country = reference1_country.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS reference2_city ON app.reference2_city = reference2_city.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS reference2_county ON app.reference2_county = reference2_county.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS reference2_state ON app.reference2_state = reference2_state.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS reference2_country ON app.reference2_country = reference2_country.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS reference3_city ON app.reference3_city = reference3_city.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS reference3_county ON app.reference3_county = reference3_county.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS reference3_state ON app.reference3_state = reference3_state.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS reference3_country ON app.reference3_country = reference3_country.code

				WHERE app.id = ". $id ;
		//echo '<br> sql '.$query;
		$db->setQuery($query);
		$resume = $db->loadObject();
		return $resume;
	}
	function & getStatebyId($c_id)
	{
		if (is_numeric($c_id) == false) return false;
		$db = & JFactory :: getDBO();
		$query = "SELECT * FROM #__wrecruit_states WHERE id = ".$c_id;
		$db->setQuery($query);
		$state = $db->loadObject();
		return $state;
	}

/* STRAT EXPORT RESUMES */
	function setExport($jobid){
		$db = &$this->getDBO();
		if (is_numeric($jobid) == false) return false;
		if (($jobid == 0) || ($jobid == '')) return false;
		$viewvalue = $this->validateViews();
		if($viewvalue != 1){
			return 	 false;

		}
		$query = "SELECT * 	from exportresume  where jobid =".$jobid;
		$db->setQuery($query);
		$result = $db->loadAssocList();
		if(!$result){
			$this->setError($this->_db->getErrorMsg());
			//echo $this->_db->getErrorMsg();
			return false;
		}else{
			// If the query doesn't work..
			if (!$db->query() ){
				echo "<script>alert('Please report your problem.');
				window.history.go(-1);</script>\n";      
			}   
			$result = $this->makeArrayForExport($result);
			// Empty data vars
			$data = "" ;
			// We need tabbed data
			$sep = "\t";
			$fields = (array_keys($result[0]));
			// Count all fields(will be the collumns
			$columns = count($fields);
			// Put the name of all fields to $out. 
			for ($i = 0; $i < $columns; $i++) {
				$data .= $fields[$i].$sep;
			}
			$data .= "\n";
			// Counting rows and push them into a for loop
			for($k=0; $k < count( $result ); $k++) {
				$row = $result[$k];
				$line = '';
				// Now replace several things for MS Excel
				foreach ($row as $value) {
					$value = str_replace('"', '""', $value);
					$line .= '"' . $value . '"' . "\t";
				}
				$data .= trim($line)."\n";
			}
			$data = str_replace("\r","",$data);
			// If count rows is nothing show o records.
			if (count( $result ) == 0) {		
				$data .= "\n(0) Records Found!\n";
			}
			return $data;
		}	
	}
	function makeArrayForExport($result){
		foreach($result as $r){
			$myarr['application_title'] = $r['application_title'];
			$myarr['first_name'] = $r['first_name'];
			$myarr['last_name'] = $r['last_name'];
			$myarr['middle_name'] = $r['middle_name'];
			$myarr['categorytitle'] = $r['categorytitle'];
			$myarr['rangestart'] = $r['rangestart'];
			$myarr['jobtypetitle'] = $r['jobtypetitle'];
			$myarr['heighesteducationtitle'] = $r['heighesteducationtitle'];
			$myarr['gender'] = $r['gender'];
			$myarr['email_address'] = $r['email_address'];
			$myarr['home_phone'] = $r['home_phone'];
			$myarr['work_phone'] = $r['work_phone'];
			$myarr['cell'] = $r['cell'];
			$myarr['iamavailable'] = $r['iamavailable'];
			$myarr['searchable'] = $r['searchable'];
			$myarr['photo'] = $r['photo'];
			$myarr['job_category'] = $r['job_category'];
			$myarr['jobsalaryrange'] = $r['jobsalaryrange'];
			$myarr['jobtype'] = $r['jobtype'];
			$myarr['heighestfinisheducation'] = $r['heighestfinisheducation'];
			if($r['address_city2']) $myarr['address city'] =$r['address_city2']; else $myarr['address city'] =$r['address_city'];
			if($r['address_county2']) $myarr['address county'] = $r['address_county2']; else $myarr['address county'] = $r['address_county'];
			if($r['address_state2']) $myarr['address state'] = $r['address_state2']; else $myarr['address state'] = $r['address_state'];
			if($r['address_country2']) $myarr['address country'] = $r['address_country2']; else $myarr['address country'] = $r['address_country'];
			$myarr['address_zipcode'] = $r['address_zipcode'];
			$myarr['address'] = $r['address'];
			$myarr['institute'] = $r['institute'];
			if($r['institute_city2']) $myarr['institute city'] = $r['institute_city2']; else $myarr['institute city'] = $r['institute_city'];
			if($r['institute_county2']) $myarr['institute county'] = $r['institute_county2']; else $myarr['institute county'] = $r['institute_county'];
			if($r['institute_state2']) $myarr['institute state'] = $r['institute_state2']; else $myarr['institute state'] = $r['institute_state'];
			if($r['institute_country2']) $myarr['institute country'] = $r['institute_country2']; else $myarr['institute country'] = $r['institute_country'];
			$myarr['institute_address'] = $r['institute_address'];
			$myarr['institute_certificate_name'] = $r['institute_certificate_name'];
			$myarr['institute_study_area'] = $r['institute_study_area'];
			$myarr['employer'] = $r['employer'];
			$myarr['employer_position'] = $r['employer_position'];
			$myarr['employer_resp'] = $r['employer_resp'];
			$myarr['employer_pay_upon_leaving'] = $r['employer_pay_upon_leaving'];
			$myarr['employer_supervisor'] = $r['employer_supervisor'];
			$myarr['employer_from_date'] = $r['employer_from_date'];
			$myarr['employer_to_date'] = $r['employer_to_date'];
			$myarr['employer_leave_reason'] = $r['employer_leave_reason'];
			if($r['employer_city2']) $myarr['employer city'] = $r['employer_city2']; else $myarr['employer city'] = $r['employer_city'];
			if($r['employer_county2']) $myarr['employer county'] = $r['employer_county2']; else $myarr['employer county'] = $r['employer_county'];
			if($r['employer_state2']) $myarr['employer state'] = $r['employer_state2']; else $myarr['employer state'] = $r['employer_state'];
			if($r['employer_country2']) $myarr['employer country'] = $r['employer_country2']; else $myarr['employer country'] = $r['employer_country'];
			$myarr['employer_zip'] = $r['employer_zip'];
			$myarr['employer_phone'] = $r['employer_phone'];
			$myarr['employer_address'] = $r['employer_address'];
			$myarr['institute1'] = $r['institute1'];
			if($r['institute1_city2']) $myarr['institute1 city'] = $r['institute1_city2']; else $myarr['institute1 city'] = $r['institute1_city'];
			if($r['institute1_county2']) $myarr['institute1 county'] = $r['institute1_county2']; else $myarr['institute1 county'] = $r['institute1_county'];
			if($r['institute1_state2']) $myarr['institute1 state'] = $r['institute1_state2']; else $myarr['institute1 state'] = $r['institute1_state'];
			if($r['institute1_country2']) $myarr['institute1 country'] = $r['institute1_country2']; else $myarr['institute1 country'] = $r['institute1_country'];
			$myarr['institute1_address'] = $r['institute1_address'];
			$myarr['institute1_certificate_name'] = $r['institute1_certificate_name'];
			$myarr['institute2'] = $r['institute2'];
			if($r['institute2_city2']) $myarr['institute2 city'] = $r['institute2_city2']; else $myarr['institute2 city'] = $r['institute2_city'];
			if($r['institute2_county2']) $myarr['institute2 county'] = $r['institute2_county2']; else $myarr['institute2 county'] = $r['institute2_county'];
			if($r['institute2_state2']) $myarr['institute2 state'] = $r['institute2_state2']; else $myarr['institute2 state'] = $r['institute2_state'];
			if($r['institute2_country2']) $myarr['institute2 country'] = $r['institute2_country2']; else $myarr['institute2 country'] = $r['institute2_country'];
			$myarr['institute2_address'] = $r['institute2_address'];
			$myarr['institute2_certificate_name'] = $r['institute2_certificate_name'];
			$myarr['institute2_study_area'] = $r['institute2_study_area'];
			$myarr['institute3'] = $r['institute3'];
			if($r['institute3_city2']) $myarr['institute3 city'] = $r['institute3_city2']; else $myarr['institute3 city'] = $r['institute3_city'];
			if($r['institute3_county2']) $myarr['institute3 county'] = $r['institute3_county2']; else $myarr['institute3 county'] = $r['institute3_county'];
			if($r['institute3_state2']) $myarr['institute3 state'] = $r['institute3_state2']; else $myarr['institute3 state'] = $r['institute3_state'];
			if($r['institute3_country2']) $myarr['institute3 country'] = $r['institute3_country2']; else $myarr['institute3 country'] = $r['institute3_country'];
			$myarr['institute3_address'] = $r['institute3_address'];
			$myarr['institute3_study_area'] = $r['institute3_study_area'];
			$myarr['employer1'] = $r['employer1'];
			$myarr['employer1_position'] = $r['employer1_position'];
			$myarr['employer1_resp'] = $r['employer1_resp'];
			$myarr['employer1_pay_upon_leaving'] = $r['employer1_pay_upon_leaving'];
			$myarr['employer1_supervisor'] = $r['employer1_supervisor'];
			$myarr['employer1_from_date'] = $r['employer1_from_date'];
			$myarr['employer1_to_date'] = $r['employer1_to_date'];
			if($r['employer1_city2']) $myarr['employer1 city'] = $r['employer1_city2']; else $myarr['employer1 city'] = $r['employer1_city'];
			if($r['employer1_county2']) $myarr['employer1 county'] = $r['employer1_county2']; else $myarr['employer1 county'] = $r['employer1_county'];
			if($r['employer1_state2']) $myarr['employer1 state'] = $r['employer1_state2']; else $myarr['employer1 state'] = $r['employer1_state'];
			if($r['employer1_country2']) $myarr['employer1 country'] = $r['employer1_country2']; else $myarr['employer1 country'] = $r['employer1_country'];
			$myarr['employer1_zip'] = $r['employer1_zip'];
			$myarr['employer1_phone'] = $r['employer1_phone'];
			$myarr['employer1_address'] = $r['employer1_address'];
			$myarr['employer2'] = $r['employer2'];
			$myarr['employer2_position'] = $r['employer2_position'];
			$myarr['employer2_resp'] = $r['employer2_resp'];
			$myarr['employer2_pay_upon_leaving'] = $r['employer2_pay_upon_leaving'];
			$myarr['employer2_supervisor'] = $r['employer2_supervisor'];
			$myarr['employer2_from_date'] = $r['employer2_from_date'];
			$myarr['employer2_to_date'] = $r['employer2_to_date'];
			$myarr['employer2_leave_reason'] = $r['employer2_leave_reason'];
			if($r['employer2_city2']) $myarr['employer2 city'] = $r['employer2_city2']; else $myarr['employer2 city'] = $r['employer2_city'];
			if($r['employer2_county2']) $myarr['employer2 county'] = $r['employer2_county2']; else $myarr['employer2 county'] = $r['employer2_county'];
			if($r['employer2_state2']) $myarr['employer2 state'] = $r['employer2_state2']; else $myarr['employer2 state'] = $r['employer2_state'];
			if($r['employer2_country2']) $myarr['employer2 country'] = $r['employer2_country2']; else $myarr['employer2 country'] = $r['employer2_country'];
			$myarr['employer2_zip'] = $r['employer2_zip'];
			$myarr['employer2_address'] = $r['employer2_address'];
			$myarr['employer2_phone'] = $r['employer2_phone'];
			$myarr['employer3'] = $r['employer3'];
			$myarr['employer3_position'] = $r['employer3_position'];
			$myarr['employer3_resp'] = $r['employer3_resp'];
			$myarr['employer3_pay_upon_leaving'] = $r['employer3_pay_upon_leaving'];
			$myarr['employer3_supervisor'] = $r['employer3_supervisor'];
			$myarr['employer3_from_date'] = $r['employer3_from_date'];
			$myarr['employer3_to_date'] = $r['employer3_to_date'];
			$myarr['employer3_leave_reason'] = $r['employer3_leave_reason'];
			if($r['employer3_city2']) $myarr['employer3 city'] = $r['employer3_city2']; else $myarr['employer3 city'] = $r['employer3_city'];
			if($r['employer3_county2']) $myarr['employer3 county'] = $r['employer3_county2']; else $myarr['employer3 county'] = $r['employer3_county'];
			if($r['employer3_state2']) $myarr['employer3 state'] = $r['employer3_state2']; else $myarr['employer3 state'] = $r['employer3_state'];
			if($r['employer3_country2']) $myarr['employer3 country'] = $r['employer3_country2']; else $myarr['employer3 country'] = $r['employer3_country'];
			$myarr['employer3_zip'] = $r['employer3_zip'];
			$myarr['employer3_phone'] = $r['employer3_phone'];
			$myarr['langugage_reading'] = $r['langugage_reading'];
			$myarr['langugage_writing'] = $r['langugage_writing'];
			$myarr['langugage_undarstanding'] = $r['langugage_undarstanding'];
			$myarr['langugage_where_learned'] = $r['langugage_where_learned'];
			$myarr['language1'] = $r['language1'];
			$myarr['langugage1_reading'] = $r['langugage1_reading'];
			$myarr['langugage1_writing'] = $r['langugage1_writing'];
			$myarr['langugage1_undarstanding'] = $r['langugage1_undarstanding'];
			$myarr['langugage1_where_learned'] = $r['langugage1_where_learned'];
			$myarr['language2'] = $r['language2'];
			$myarr['langugage2_reading'] = $r['langugage2_reading'];
			$myarr['langugage2_writing'] = $r['langugage2_writing'];
			$myarr['langugage2_undarstanding'] = $r['langugage2_undarstanding'];
			$myarr['langugage2_where_learned'] = $r['langugage2_where_learned'];
			$myarr['language3'] = $r['language3'];
			$myarr['langugage3_reading'] = $r['langugage3_reading'];
			$myarr['langugage3_writing'] = $r['langugage3_writing'];
			$myarr['langugage3_undarstanding'] = $r['langugage3_undarstanding'];
			$myarr['langugage3_where_learned'] = $r['langugage3_where_learned'];
			$myarr['date_start'] = $r['date_start'];
			$myarr['desired_salary'] = $r['desired_salary'];
			$myarr['can_work'] = $r['can_work'];
			$myarr['available'] = $r['available'];
			$myarr['unalailable'] = $r['unalailable'];
			$myarr['total_experience'] = $r['total_experience'];
			$myarr['skills'] = $r['skills'];
			$myarr['driving_license'] = $r['driving_license'];
			$myarr['license_no'] = $r['license_no'];
			$myarr['license_country'] = $r['license_country'];
			$myarr['reference'] = $r['reference'];
			$myarr['reference_name'] = $r['reference_name'];
			if($r['reference_city2']) $myarr['reference city'] = $r['reference_city2']; else $myarr['reference city'] = $r['reference_city'];
			if($r['reference_county2']) $myarr['reference county'] = $r['reference_county2']; else $myarr['reference county'] = $r['reference_county'];
			if($r['reference_state2']) $myarr['reference state'] = $r['reference_state2']; else $myarr['reference state'] = $r['reference_state'];
			if($r['reference_country2']) $myarr['reference country'] = $r['reference_country2']; else $myarr['reference country'] = $r['reference_country'];
			$myarr['reference_zipcode'] = $r['reference_zipcode'];
			$myarr['reference_address'] = $r['reference_address'];
			$myarr['reference_phone'] = $r['reference_phone'];
			$myarr['reference_relation'] = $r['reference_relation'];
			$myarr['reference_years'] = $r['reference_years'];
			$myarr['reference1'] = $r['reference1'];
			$myarr['reference1_name'] = $r['reference1_name'];
			if($r['reference1_city2']) $myarr['reference1 city'] = $r['reference1_city2']; else $myarr['reference1 city'] = $r['reference1_city'];
			if($r['reference1_county2']) $myarr['reference1 county'] = $r['reference1_county2']; else $myarr['reference1 county'] = $r['reference1_county'];
			if($r['reference1_state2']) $myarr['reference1 state'] = $r['reference1_state2']; else $myarr['reference1 state'] = $r['reference1_state'];
			if($r['reference1_country2']) $myarr['reference1 country'] = $r['reference1_country2']; else $myarr['reference1 country'] = $r['reference1_country'];
			$myarr['reference1_address'] = $r['reference1_address'];
			$myarr['reference1_phone'] = $r['reference1_phone'];
			$myarr['reference1_relation'] = $r['reference1_relation'];
			$myarr['reference1_years'] = $r['reference1_years'];
			$myarr['reference2'] = $r['reference2'];
			$myarr['reference2_name'] = $r['reference2_name'];
			$myarr['reference2_country'] = $r['reference2_country'];
			$myarr['reference2_state'] = $r['reference2_state'];
			$myarr['reference2_county'] = $r['reference2_county'];
			$myarr['reference2_city'] = $r['reference2_city'];
			$myarr['reference2_address'] = $r['reference2_address'];
			$myarr['reference2_phone'] = $r['reference2_phone'];
			$myarr['reference2_relation'] = $r['reference2_relation'];
			$myarr['reference2_years'] = $r['reference2_years'];
			$myarr['reference3'] = $r['reference3'];
			$myarr['reference3_name'] = $r['reference3_name'];
			$myarr['reference3_country'] = $r['reference3_country'];
			$myarr['reference3_state'] = $r['reference3_state'];
			$myarr['reference3_county'] = $r['reference3_county'];
			$myarr['reference3_city'] = $r['reference3_city'];
			$myarr['reference3_address'] = $r['reference3_address'];
			$myarr['reference3_phone'] = $r['reference3_phone'];
			$myarr['reference3_relation'] = $r['reference3_relation'];
			$myarr['reference3_years'] = $r['reference3_years'];
			if($r['address1_city2']) $myarr['address1 city'] = $r['address1_city2']; else $myarr['address1 city'] = $r['address1_city'];
			if($r['address1_county2']) $myarr['address1 county'] = $r['address1_county2']; else $myarr['address1 county'] = $r['address1_county'];
			if($r['address1_state2']) $myarr['address1 state'] = $r['address1_state2']; else $myarr['address1 state'] = $r['address1_state'];
			if($r['address1_country2']) $myarr['address1 country'] = $r['address1_country2']; else $myarr['address1 country'] = $r['address1_country'];
			$myarr['address1_zipcode'] = $r['address1_zipcode'];
			$myarr['address1'] = $r['address1'];
			if($r['address2_city2']) $myarr['address2 city'] = $r['address2_city2']; else $myarr['address2 city'] = $r['address2_city'];
			if($r['address2_county2']) $myarr['address2 county'] = $r['address2_county2']; else $myarr['address2 county'] = $r['address2_county'];
			if($r['address2_state2']) $myarr['address2 state'] = $r['address2_state2']; else $myarr['address2 state'] = $r['address2_state'];
			if($r['address2_country2']) $myarr['address2 country'] = $r['address2_country2']; else $myarr['address2 country'] = $r['address2_country'];
			$myarr['address2_zipcode'] = $r['address2_zipcode'];
			$myarr['address2'] = $r['address2'];
			$myarr['reference1_zipcode'] = $r['reference1_zipcode'];
			$myarr['reference2_zipcode'] = $r['reference2_zipcode'];
			$myarr['reference3_zipcode'] = $r['reference3_zipcode'];
			$myarr['packageid'] = $r['packageid'];
			$myarr['paymenthistoryid'] = $r['paymenthistoryid'];
			$myarr['status'] = $r['status'];
			$myarr['Apply Date'] = $r['Apply Date']; 
			$myarr['Comments'] = $r['Comments'];

			$returnvalue[] = $myarr; 	

		}
		//print_r($returnvalue);
		return $returnvalue;
	
	}
/* END EXPORT RESUMES */
	function validateViews(){
		$db = &$this->getDBO();
		$db->setQuery('SELECT id FROM view_resumes');

		if (!$view = $db->loadObject()){
			//echo $this->_db->getErrorMsg();
			if($this->createViews() == 1) return true; else return false;
		}else return true;
	}
	function createViews(){
		$db = &$this->getDBO();
		$query="CREATE VIEW `view_resumes`AS 
				SELECT `cat`.`cat_title` AS `categorytitle`,`salary`.`rangestart` AS `rangestart`,`salary`.`rangeend` AS `rangeend`,`jobtype`.`title` AS `jobtypetitle`,`heighesteducation`.`title` AS `heighesteducationtitle`,`nationality_country`.`name` AS `nationalitycountry`,`address_city`.`name` AS `address_city2`,`address_county`.`name` AS `address_county2`,`address_state`.`name` AS `address_state2`,`address_country`.`name` AS `address_country2`,`address1_city`.`name` AS `address1_city2`,`address1_county`.`name` AS `address1_county2`,`address1_state`.`name` AS `address1_state2`,`address1_country`.`name` AS `address1_country2`,`address2_city`.`name` AS `address2_city2`,`address2_county`.`name` AS `address2_county2`,`address2_state`.`name` AS `address2_state2`,`address2_country`.`name` AS `address2_country2`,`institute_city`.`name` AS `institute_city2`,`institute_county`.`name` AS `institute_county2`,`institute_state`.`name` AS `institute_state2`,`institute_country`.`name` AS `institute_country2`,`institute1_city`.`name` AS `institute1_city2`,`institute1_county`.`name` AS `institute1_county2`,`institute1_state`.`name` AS `institute1_state2`,`institute1_country`.`name` AS `institute1_country2`,`institute2_city`.`name` AS `institute2_city2`,`institute2_county`.`name` AS `institute2_county2`,`institute2_state`.`name` AS `institute2_state2`,`institute2_country`.`name` AS `institute2_country2`,`institute3_city`.`name` AS `institute3_city2`,`institute3_county`.`name` AS `institute3_county2`,`institute3_state`.`name` AS `institute3_state2`,`institute3_country`.`name` AS `institute3_country2`,`employer_city`.`name` AS `employer_city2`,`employer_county`.`name` AS `employer_county2`,`employer_state`.`name` AS `employer_state2`,`employer_country`.`name` AS `employer_country2`,`employer1_city`.`name` AS `employer1_city2`,`employer1_county`.`name` AS `employer1_county2`,`employer1_state`.`name` AS `employer1_state2`,`employer1_country`.`name` AS `employer1_country2`,`employer2_city`.`name` AS `employer2_city2`,`employer2_county`.`name` AS `employer2_county2`,`employer2_state`.`name` AS `employer2_state2`,`employer2_country`.`name` AS `employer2_country2`,`employer3_city`.`name` AS `employer3_city2`,`employer3_county`.`name` AS `employer3_county2`,`employer3_state`.`name` AS `employer3_state2`,`employer3_country`.`name` AS `employer3_country2`,`reference_city`.`name` AS `reference_city2`,`reference_county`.`name` AS `reference_county2`,`reference_state`.`name` AS `reference_state2`,`reference_country`.`name` AS `reference_country2`,`reference1_city`.`name` AS `reference1_city2`,`reference1_county`.`name` AS `reference1_county2`,`reference1_state`.`name` AS `reference1_state2`,`reference1_country`.`name` AS `reference1_country2`,`resume`.`id` AS `id`,`resume`.`uid` AS `uid`,`resume`.`application_title` AS `application_title`,`resume`.`first_name` AS `first_name`,`resume`.`last_name` AS `last_name`,`resume`.`middle_name` AS `middle_name`,`resume`.`gender` AS `gender`,`resume`.`email_address` AS `email_address`,`resume`.`home_phone` AS `home_phone`,`resume`.`work_phone` AS `work_phone`,`resume`.`cell` AS `cell`,`resume`.`nationality` AS `iamavailable`,`resume`.`searchable` AS `searchable`,`resume`.`photo` AS `photo`,`resume`.`job_category` AS `job_category`,`resume`.`jobsalaryrange` AS `jobsalaryrange`,`resume`.`jobtype` AS `jobtype`,`resume`.`heighestfinisheducation` AS `heighestfinisheducation`,`resume`.`address_country` AS `address_country`,`resume`.`address_state` AS `address_state`,`resume`.`address_city` AS `address_city`,`resume`.`address_zipcode` AS `address_zipcode`,`resume`.`address` AS `address`,`resume`.`institute` AS `institute`,`resume`.`institute_country` AS `institute_country`,`resume`.`institute_state` AS `institute_state`,`resume`.`institute_county` AS `institute_county`,`resume`.`institute_city` AS `institute_city`,`resume`.`institute_address` AS `institute_address`,`resume`.`institute_certificate_name` AS `institute_certificate_name`,`resume`.`institute_study_area` AS `institute_study_area`,`resume`.`employer` AS `employer`,`resume`.`employer_position` AS `employer_position`,`resume`.`employer_resp` AS `employer_resp`,`resume`.`employer_pay_upon_leaving` AS `employer_pay_upon_leaving`,`resume`.`employer_supervisor` AS `employer_supervisor`,`resume`.`employer_from_date` AS `employer_from_date`,`resume`.`employer_to_date` AS `employer_to_date`,`resume`.`employer_leave_reason` AS `employer_leave_reason`,`resume`.`employer_country` AS `employer_country`,`resume`.`employer_state` AS `employer_state`,`resume`.`employer_county` AS `employer_county`,`resume`.`employer_city` AS `employer_city`,`resume`.`employer_zip` AS `employer_zip`,`resume`.`employer_phone` AS `employer_phone`,`resume`.`employer_address` AS `employer_address`,`resume`.`institute1` AS `institute1`,`resume`.`institute1_country` AS `institute1_country`,`resume`.`institute1_state` AS `institute1_state`,`resume`.`institute1_county` AS `institute1_county`,`resume`.`institute1_city` AS `institute1_city`,`resume`.`institute1_address` AS `institute1_address`,`resume`.`institute1_certificate_name` AS `institute1_certificate_name`,`resume`.`institute1_study_area` AS `institute2`,`resume`.`institute2_country` AS `institute2_country`,`resume`.`institute2_state` AS `institute2_state`,`resume`.`institute2_county` AS `institute2_county`,`resume`.`institute2_city` AS `institute2_city`,`resume`.`institute2_address` AS `institute2_address`,`resume`.`institute2_certificate_name` AS `institute2_certificate_name`,`resume`.`institute2_study_area` AS `institute2_study_area`,`resume`.`institute3` AS `institute3`,`resume`.`institute3_country` AS `institute3_country`,`resume`.`institute3_state` AS `institute3_state`,`resume`.`institute3_county` AS `institute3_county`,`resume`.`institute3_city` AS `institute3_city`,`resume`.`institute3_address` AS `institute3_address`,`resume`.`institute3_study_area` AS `institute3_study_area`,`resume`.`institute3_certificate_name` AS `employer1`,`resume`.`employer1_position` AS `employer1_position`,`resume`.`employer1_resp` AS `employer1_resp`,`resume`.`employer1_pay_upon_leaving` AS `employer1_pay_upon_leaving`,`resume`.`employer1_supervisor` AS `employer1_supervisor`,`resume`.`employer1_from_date` AS `employer1_from_date`,`resume`.`employer1_to_date` AS `employer1_to_date`,`resume`.`employer1_leave_reason` AS `employer1_country`,`resume`.`employer1_state` AS `employer1_state`,`resume`.`employer1_county` AS `employer1_county`,`resume`.`employer1_city` AS `employer1_city`,`resume`.`employer1_zip` AS `employer1_zip`,`resume`.`employer1_phone` AS `employer1_phone`,`resume`.`employer1_address` AS `employer1_address`,`resume`.`employer2` AS `employer2`,`resume`.`employer2_position` AS `employer2_position`,`resume`.`employer2_resp` AS `employer2_resp`,`resume`.`employer2_pay_upon_leaving` AS `employer2_pay_upon_leaving`,`resume`.`employer2_supervisor` AS `employer2_supervisor`,`resume`.`employer2_from_date` AS `employer2_from_date`,`resume`.`employer2_to_date` AS `employer2_to_date`,`resume`.`employer2_leave_reason` AS `employer2_leave_reason`,`resume`.`employer2_country` AS `employer2_country`,`resume`.`employer2_state` AS `employer2_state`,`resume`.`employer2_county` AS `employer2_county`,`resume`.`employer2_city` AS `employer2_city`,`resume`.`employer2_zip` AS `employer2_zip`,`resume`.`employer2_address` AS `employer2_address`,`resume`.`employer2_phone` AS `employer2_phone`,`resume`.`employer3` AS `employer3`,`resume`.`employer3_position` AS `employer3_position`,`resume`.`employer3_resp` AS `employer3_resp`,`resume`.`employer3_pay_upon_leaving` AS `employer3_pay_upon_leaving`,`resume`.`employer3_supervisor` AS `employer3_supervisor`,`resume`.`employer3_from_date` AS `employer3_from_date`,`resume`.`employer3_to_date` AS `employer3_to_date`,`resume`.`employer3_leave_reason` AS `employer3_leave_reason`,`resume`.`employer3_country` AS `employer3_country`,`resume`.`employer3_state` AS `employer3_state`,`resume`.`employer3_county` AS `employer3_county`,`resume`.`employer3_city` AS `employer3_city`,`resume`.`employer3_zip` AS `employer3_zip`,`resume`.`employer3_address` AS `employer3_phone`,`resume`.`langugage_reading` AS `langugage_reading`,`resume`.`langugage_writing` AS `langugage_writing`,`resume`.`langugage_undarstanding` AS `langugage_undarstanding`,`resume`.`langugage_where_learned` AS `langugage_where_learned`,`resume`.`language1` AS `language1`,`resume`.`langugage1_reading` AS `langugage1_reading`,`resume`.`langugage1_writing` AS `langugage1_writing`,`resume`.`langugage1_undarstanding` AS `langugage1_undarstanding`,`resume`.`langugage1_where_learned` AS `langugage1_where_learned`,`resume`.`language2` AS `language2`,`resume`.`langugage2_reading` AS `langugage2_reading`,`resume`.`langugage2_writing` AS `langugage2_writing`,`resume`.`langugage2_undarstanding` AS `langugage2_undarstanding`,`resume`.`langugage2_where_learned` AS `langugage2_where_learned`,`resume`.`language3` AS `language3`,`resume`.`langugage3_reading` AS `langugage3_reading`,`resume`.`langugage3_writing` AS `langugage3_writing`,`resume`.`langugage3_undarstanding` AS `langugage3_undarstanding`,`resume`.`langugage3_where_learned` AS `langugage3_where_learned`,`resume`.`date_start` AS `date_start`,`resume`.`desired_salary` AS `desired_salary`,`resume`.`can_work` AS `can_work`,`resume`.`available` AS `available`,`resume`.`unalailable` AS `unalailable`,`resume`.`total_experience` AS `total_experience`,`resume`.`skills` AS `skills`,`resume`.`driving_license` AS `driving_license`,`resume`.`license_no` AS `license_no`,`resume`.`license_country` AS `license_country`,`resume`.`reference` AS `reference`,`resume`.`reference_name` AS `reference_name`,`resume`.`reference_country` AS `reference_country`,`resume`.`reference_state` AS `reference_state`,`resume`.`reference_county` AS `reference_county`,`resume`.`reference_city` AS `reference_city`,`resume`.`reference_zipcode` AS `reference_zipcode`,`resume`.`reference_address` AS `reference_address`,`resume`.`reference_phone` AS `reference_phone`,`resume`.`reference_relation` AS `reference_relation`,`resume`.`reference_years` AS `reference_years`,`resume`.`reference1` AS `reference1`,`resume`.`reference1_name` AS `reference1_name`,`resume`.`reference1_country` AS `reference1_country`,`resume`.`reference1_state` AS `reference1_state`,`resume`.`reference1_county` AS `reference1_city`,`resume`.`reference1_address` AS `reference1_address`,`resume`.`reference1_phone` AS `reference1_phone`,`resume`.`reference1_relation` AS `reference1_relation`,`resume`.`reference1_years` AS `reference1_years`,`resume`.`reference2` AS `reference2`,`resume`.`reference2_name` AS `reference2_name`,`resume`.`reference2_country` AS `reference2_country`,`resume`.`reference2_state` AS `reference2_state`,`resume`.`reference2_county` AS `reference2_county`,`resume`.`reference2_city` AS `reference2_city`,`resume`.`reference2_address` AS `reference2_address`,`resume`.`reference2_phone` AS `reference2_phone`,`resume`.`reference2_relation` AS `reference2_relation`,`resume`.`reference2_years` AS `reference2_years`,`resume`.`reference3` AS `reference3`,`resume`.`reference3_name` AS `reference3_name`,`resume`.`reference3_country` AS `reference3_country`,`resume`.`reference3_state` AS `reference3_state`,`resume`.`reference3_county` AS `reference3_county`,`resume`.`reference3_city` AS `reference3_city`,`resume`.`reference3_address` AS `reference3_address`,`resume`.`reference3_phone` AS `reference3_phone`,`resume`.`reference3_relation` AS `reference3_relation`,`resume`.`reference3_years` AS `reference3_years`,`resume`.`address1_country` AS `address1_country`,`resume`.`address1_state` AS `address1_state`,`resume`.`address1_county` AS `address1_county`,`resume`.`address1_city` AS `address1_city`,`resume`.`address1_zipcode` AS `address1_zipcode`,`resume`.`address1` AS `address1`,`resume`.`address2_country` AS `address2_country`,`resume`.`address2_state` AS `address2_state`,`resume`.`address2_county` AS `address2_county`,`resume`.`address2_city` AS `address2_city`,`resume`.`address2_zipcode` AS `address2_zipcode`,`resume`.`address2` AS `address2`,`resume`.`reference1_zipcode` AS `reference1_zipcode`,`resume`.`reference2_zipcode` AS `reference2_zipcode`,`resume`.`reference3_zipcode` AS `reference3_zipcode`,`resume`.`packageid` AS `packageid`,`resume`.`paymenthistoryid` AS `paymenthistoryid`,`resume`.`status` AS `status` from (((((((((((((((((((((((((((((((((((((((((((((((((((((((((`#__wrecruit_resume` `resume` join `#__wrecruit_categories` `cat` on((`resume`.`job_category` = `cat`.`id`))) join `#__wrecruit_jobtypes` `jobtype` on((`resume`.`jobtype` = `jobtype`.`id`))) left join `#__wrecruit_heighesteducation` `heighesteducation` on((`resume`.`heighestfinisheducation` = `heighesteducation`.`id`))) left join `#__wrecruit_countries` `nationality_country` on((`resume`.`nationality` = `nationality_country`.`code`))) left join `#__wrecruit_salaryrange` `salary` on((`resume`.`jobsalaryrange` = `salary`.`id`))) left join `#__wrecruit_cities` `address_city` on((`resume`.`address_city` = `address_city`.`code`))) left join `#__wrecruit_counties` `address_county` on((`resume`.`address_county` = `address_county`.`code`))) left join `#__wrecruit_states` `address_state` on((`resume`.`address_state` = `address_state`.`code`))) left join `#__wrecruit_countries` `address_country` on((`resume`.`address_country` = `address_country`.`code`))) left join `#__wrecruit_cities` `address1_city` on((`resume`.`address1_city` = `address1_city`.`code`))) left join `#__wrecruit_counties` `address1_county` on((`resume`.`address1_county` = `address1_county`.`code`))) left join `#__wrecruit_states` `address1_state` on((`resume`.`address1_state` = `address1_state`.`code`))) left join `#__wrecruit_countries` `address1_country` on((`resume`.`address1_country` = `address1_country`.`code`))) left join `#__wrecruit_cities` `address2_city` on((`resume`.`address2_city` = `address2_city`.`code`))) left join `#__wrecruit_counties` `address2_county` on((`resume`.`address2_county` = `address2_county`.`code`))) left join `#__wrecruit_states` `address2_state` on((`resume`.`address2_state` = `address2_state`.`code`))) left join `#__wrecruit_countries` `address2_country` on((`resume`.`address2_country` = `address2_country`.`code`))) left join `#__wrecruit_cities` `institute_city` on((`resume`.`institute_city` = `institute_city`.`code`))) left join `#__wrecruit_counties` `institute_county` on((`resume`.`institute_county` = `institute_county`.`code`))) left join `#__wrecruit_states` `institute_state` on((`resume`.`institute_state` = `institute_state`.`code`))) left join `#__wrecruit_countries` `institute_country` on((`resume`.`institute_country` = `institute_country`.`code`))) left join `#__wrecruit_cities` `institute1_city` on((`resume`.`institute1_city` = `institute1_city`.`code`))) left join `#__wrecruit_counties` `institute1_county` on((`resume`.`institute1_county` = `institute1_county`.`code`))) left join `#__wrecruit_states` `institute1_state` on((`resume`.`institute1_state` = `institute1_state`.`code`))) left join `#__wrecruit_countries` `institute1_country` on((`resume`.`institute1_country` = `institute1_country`.`code`))) left join `#__wrecruit_cities` `institute2_city` on((`resume`.`institute2_city` = `institute2_city`.`code`))) left join `#__wrecruit_counties` `institute2_county` on((`resume`.`institute2_county` = `institute2_county`.`code`))) left join `#__wrecruit_states` `institute2_state` on((`resume`.`institute2_state` = `institute2_state`.`code`))) left join `#__wrecruit_countries` `institute2_country` on((`resume`.`institute2_country` = `institute2_country`.`code`))) left join `#__wrecruit_cities` `institute3_city` on((`resume`.`institute3_city` = `institute3_city`.`code`))) left join `#__wrecruit_counties` `institute3_county` on((`resume`.`institute3_county` = `institute3_county`.`code`))) left join `#__wrecruit_states` `institute3_state` on((`resume`.`institute3_state` = `institute3_state`.`code`))) left join `#__wrecruit_countries` `institute3_country` on((`resume`.`institute3_country` = `institute3_country`.`code`))) left join `#__wrecruit_cities` `employer_city` on((`resume`.`employer_city` = `employer_city`.`code`))) left join `#__wrecruit_counties` `employer_county` on((`resume`.`employer_county` = `employer_county`.`code`))) left join `#__wrecruit_states` `employer_state` on((`resume`.`employer_state` = `employer_state`.`code`))) left join `#__wrecruit_countries` `employer_country` on((`resume`.`employer_country` = `employer_country`.`code`))) left join `#__wrecruit_cities` `employer1_city` on((`resume`.`employer1_city` = `employer1_city`.`code`))) left join `#__wrecruit_counties` `employer1_county` on((`resume`.`employer1_county` = `employer1_county`.`code`))) left join `#__wrecruit_states` `employer1_state` on((`resume`.`employer1_state` = `employer1_state`.`code`))) left join `#__wrecruit_countries` `employer1_country` on((`resume`.`employer1_country` = `employer1_country`.`code`))) left join `#__wrecruit_cities` `employer2_city` on((`resume`.`employer2_city` = `employer2_city`.`code`))) left join `#__wrecruit_counties` `employer2_county` on((`resume`.`employer2_county` = `employer2_county`.`code`))) left join `#__wrecruit_states` `employer2_state` on((`resume`.`employer2_state` = `employer2_state`.`code`))) left join `#__wrecruit_countries` `employer2_country` on((`resume`.`employer2_country` = `employer2_country`.`code`))) left join `#__wrecruit_cities` `employer3_city` on((`resume`.`employer3_city` = `employer3_city`.`code`))) left join `#__wrecruit_counties` `employer3_county` on((`resume`.`employer3_county` = `employer3_county`.`code`))) left join `#__wrecruit_states` `employer3_state` on((`resume`.`employer3_state` = `employer3_state`.`code`))) left join `#__wrecruit_countries` `employer3_country` on((`resume`.`employer3_country` = `employer3_country`.`code`))) left join `#__wrecruit_cities` `reference_city` on((`resume`.`reference_city` = `reference_city`.`code`))) left join `#__wrecruit_counties` `reference_county` on((`resume`.`reference_county` = `reference_county`.`code`))) left join `#__wrecruit_states` `reference_state` on((`resume`.`reference_state` = `reference_state`.`code`))) left join `#__wrecruit_countries` `reference_country` on((`resume`.`reference_country` = `reference_country`.`code`))) left join `#__wrecruit_cities` `reference1_city` on((`resume`.`reference1_city` = `reference1_city`.`code`))) left join `#__wrecruit_counties` `reference1_county` on((`resume`.`reference1_county` = `reference1_county`.`code`))) left join `#__wrecruit_states` `reference1_state` on((`resume`.`reference1_state` = `reference1_state`.`code`))) left join `#__wrecruit_countries` `reference1_country` on((`resume`.`reference1_country` = `reference1_country`.`code`)));
				CREATE VIEW `exportresume`AS 
				SELECT `resume`.`categorytitle` AS `categorytitle`,`resume`.`rangestart` AS `rangestart`,`resume`.`rangeend` AS `rangeend`,`resume`.`jobtypetitle` AS `jobtypetitle`,`resume`.`heighesteducationtitle` AS `heighesteducationtitle`,`resume`.`nationalitycountry` AS `nationalitycountry`,`resume`.`address_city2` AS `address_city2`,`resume`.`address_county2` AS `address_county2`,`resume`.`address_state2` AS `address_state2`,`resume`.`address_country2` AS `address_country2`,`resume`.`address1_city2` AS `address1_city2`,`resume`.`address1_county2` AS `address1_county2`,`resume`.`address1_state2` AS `address1_state2`,`resume`.`address1_country2` AS `address1_country2`,`resume`.`address2_city2` AS `address2_city2`,`resume`.`address2_county2` AS `address2_county2`,`resume`.`address2_state2` AS `address2_state2`,`resume`.`address2_country2` AS `address2_country2`,`resume`.`institute_city2` AS `institute_city2`,`resume`.`institute_county2` AS `institute_county2`,`resume`.`institute_state2` AS `institute_state2`,`resume`.`institute_country2` AS `institute_country2`,`resume`.`institute1_city2` AS `institute1_city2`,`resume`.`institute1_county2` AS `institute1_county2`,`resume`.`institute1_state2` AS `institute1_state2`,`resume`.`institute1_country2` AS `institute1_country2`,`resume`.`institute2_city2` AS `institute2_city2`,`resume`.`institute2_county2` AS `institute2_county2`,`resume`.`institute2_state2` AS `institute2_state2`,`resume`.`institute2_country2` AS `institute2_country2`,`resume`.`institute3_city2` AS `institute3_city2`,`resume`.`institute3_county2` AS `institute3_county2`,`resume`.`institute3_state2` AS `institute3_state2`,`resume`.`institute3_country2` AS `institute3_country2`,`resume`.`employer_city2` AS `employer_city2`,`resume`.`employer_county2` AS `employer_county2`,`resume`.`employer_state2` AS `employer_state2`,`resume`.`employer_country2` AS `employer_country2`,`resume`.`employer1_city2` AS `employer1_city2`,`resume`.`employer1_county2` AS `employer1_county2`,`resume`.`employer1_state2` AS `employer1_state2`,`resume`.`employer1_country2` AS `employer1_country2`,`resume`.`employer2_city2` AS `employer2_city2`,`resume`.`employer2_county2` AS `employer2_county2`,`resume`.`employer2_state2` AS `employer2_state2`,`resume`.`employer2_country2` AS `employer2_country2`,`resume`.`employer3_city2` AS `employer3_city2`,`resume`.`employer3_county2` AS `employer3_county2`,`resume`.`employer3_state2` AS `employer3_state2`,`resume`.`employer3_country2` AS `employer3_country2`,`resume`.`reference_city2` AS `reference_city2`,`resume`.`reference_county2` AS `reference_county2`,`resume`.`reference_state2` AS `reference_state2`,`resume`.`reference_country2` AS `reference_country2`,`resume`.`reference1_city2` AS `reference1_city2`,`resume`.`reference1_county2` AS `reference1_county2`,`resume`.`reference1_state2` AS `reference1_state2`,`resume`.`reference1_country2` AS `reference1_country2`,`resume`.`id` AS `id`,`resume`.`uid` AS `uid`,`resume`.`application_title` AS `application_title`,`resume`.`first_name` AS `first_name`,`resume`.`last_name` AS `last_name`,`resume`.`middle_name` AS `middle_name`,`resume`.`gender` AS `gender`,`resume`.`email_address` AS `email_address`,`resume`.`home_phone` AS `home_phone`,`resume`.`work_phone` AS `work_phone`,`resume`.`cell` AS `cell`,`resume`.`iamavailable` AS `iamavailable`,`resume`.`searchable` AS `searchable`,`resume`.`photo` AS `photo`,`resume`.`job_category` AS `job_category`,`resume`.`jobsalaryrange` AS `jobsalaryrange`,`resume`.`jobtype` AS `jobtype`,`resume`.`heighestfinisheducation` AS `heighestfinisheducation`,`resume`.`address_country` AS `address_country`,`resume`.`address_state` AS `address_state`,`resume`.`address_city` AS `address_city`,`resume`.`address_zipcode` AS `address_zipcode`,`resume`.`address` AS `address`,`resume`.`institute` AS `institute`,`resume`.`institute_country` AS `institute_country`,`resume`.`institute_state` AS `institute_state`,`resume`.`institute_county` AS `institute_county`,`resume`.`institute_city` AS `institute_city`,`resume`.`institute_address` AS `institute_address`,`resume`.`institute_certificate_name` AS `institute_certificate_name`,`resume`.`institute_study_area` AS `institute_study_area`,`resume`.`employer` AS `employer`,`resume`.`employer_position` AS `employer_position`,`resume`.`employer_resp` AS `employer_resp`,`resume`.`employer_pay_upon_leaving` AS `employer_pay_upon_leaving`,`resume`.`employer_supervisor` AS `employer_supervisor`,`resume`.`employer_from_date` AS `employer_from_date`,`resume`.`employer_to_date` AS `employer_to_date`,`resume`.`employer_leave_reason` AS `employer_leave_reason`,`resume`.`employer_country` AS `employer_country`,`resume`.`employer_state` AS `employer_state`,`resume`.`employer_county` AS `employer_county`,`resume`.`employer_city` AS `employer_city`,`resume`.`employer_zip` AS `employer_zip`,`resume`.`employer_phone` AS `employer_phone`,`resume`.`employer_address` AS `employer_address`,`resume`.`institute1` AS `institute1`,`resume`.`institute1_country` AS `institute1_country`,`resume`.`institute1_state` AS `institute1_state`,`resume`.`institute1_county` AS `institute1_county`,`resume`.`institute1_city` AS `institute1_city`,`resume`.`institute1_address` AS `institute1_address`,`resume`.`institute1_certificate_name` AS `institute1_certificate_name`,`resume`.`institute2` AS `institute2`,`resume`.`institute2_country` AS `institute2_country`,`resume`.`institute2_state` AS `institute2_state`,`resume`.`institute2_county` AS `institute2_county`,`resume`.`institute2_city` AS `institute2_city`,`resume`.`institute2_address` AS `institute2_address`,`resume`.`institute2_certificate_name` AS `institute2_certificate_name`,`resume`.`institute2_study_area` AS `institute2_study_area`,`resume`.`institute3` AS `institute3`,`resume`.`institute3_country` AS `institute3_country`,`resume`.`institute3_state` AS `institute3_state`,`resume`.`institute3_county` AS `institute3_county`,`resume`.`institute3_city` AS `institute3_city`,`resume`.`institute3_address` AS `institute3_address`,`resume`.`institute3_study_area` AS `institute3_study_area`,`resume`.`employer1` AS `employer1`,`resume`.`employer1_position` AS `employer1_position`,`resume`.`employer1_resp` AS `employer1_resp`,`resume`.`employer1_pay_upon_leaving` AS `employer1_pay_upon_leaving`,`resume`.`employer1_supervisor` AS `employer1_supervisor`,`resume`.`employer1_from_date` AS `employer1_from_date`,`resume`.`employer1_to_date` AS `employer1_to_date`,`resume`.`employer1_country` AS `employer1_country`,`resume`.`employer1_state` AS `employer1_state`,`resume`.`employer1_county` AS `employer1_county`,`resume`.`employer1_city` AS `employer1_city`,`resume`.`employer1_zip` AS `employer1_zip`,`resume`.`employer1_phone` AS `employer1_phone`,`resume`.`employer1_address` AS `employer1_address`,`resume`.`employer2` AS `employer2`,`resume`.`employer2_position` AS `employer2_position`,`resume`.`employer2_resp` AS `employer2_resp`,`resume`.`employer2_pay_upon_leaving` AS `employer2_pay_upon_leaving`,`resume`.`employer2_supervisor` AS `employer2_supervisor`,`resume`.`employer2_from_date` AS `employer2_from_date`,`resume`.`employer2_to_date` AS `employer2_to_date`,`resume`.`employer2_leave_reason` AS `employer2_leave_reason`,`resume`.`employer2_country` AS `employer2_country`,`resume`.`employer2_state` AS `employer2_state`,`resume`.`employer2_county` AS `employer2_county`,`resume`.`employer2_city` AS `employer2_city`,`resume`.`employer2_zip` AS `employer2_zip`,`resume`.`employer2_address` AS `employer2_address`,`resume`.`employer2_phone` AS `employer2_phone`,`resume`.`employer3` AS `employer3`,`resume`.`employer3_position` AS `employer3_position`,`resume`.`employer3_resp` AS `employer3_resp`,`resume`.`employer3_pay_upon_leaving` AS `employer3_pay_upon_leaving`,`resume`.`employer3_supervisor` AS `employer3_supervisor`,`resume`.`employer3_from_date` AS `employer3_from_date`,`resume`.`employer3_to_date` AS `employer3_to_date`,`resume`.`employer3_leave_reason` AS `employer3_leave_reason`,`resume`.`employer3_country` AS `employer3_country`,`resume`.`employer3_state` AS `employer3_state`,`resume`.`employer3_county` AS `employer3_county`,`resume`.`employer3_city` AS `employer3_city`,`resume`.`employer3_zip` AS `employer3_zip`,`resume`.`employer3_phone` AS `employer3_phone`,`resume`.`langugage_reading` AS `langugage_reading`,`resume`.`langugage_writing` AS `langugage_writing`,`resume`.`langugage_undarstanding` AS `langugage_undarstanding`,`resume`.`langugage_where_learned` AS `langugage_where_learned`,`resume`.`language1` AS `language1`,`resume`.`langugage1_reading` AS `langugage1_reading`,`resume`.`langugage1_writing` AS `langugage1_writing`,`resume`.`langugage1_undarstanding` AS `langugage1_undarstanding`,`resume`.`langugage1_where_learned` AS `langugage1_where_learned`,`resume`.`language2` AS `language2`,`resume`.`langugage2_reading` AS `langugage2_reading`,`resume`.`langugage2_writing` AS `langugage2_writing`,`resume`.`langugage2_undarstanding` AS `langugage2_undarstanding`,`resume`.`langugage2_where_learned` AS `langugage2_where_learned`,`resume`.`language3` AS `language3`,`resume`.`langugage3_reading` AS `langugage3_reading`,`resume`.`langugage3_writing` AS `langugage3_writing`,`resume`.`langugage3_undarstanding` AS `langugage3_undarstanding`,`resume`.`langugage3_where_learned` AS `langugage3_where_learned`,`resume`.`date_start` AS `date_start`,`resume`.`desired_salary` AS `desired_salary`,`resume`.`can_work` AS `can_work`,`resume`.`available` AS `available`,`resume`.`unalailable` AS `unalailable`,`resume`.`total_experience` AS `total_experience`,`resume`.`skills` AS `skills`,`resume`.`driving_license` AS `driving_license`,`resume`.`license_no` AS `license_no`,`resume`.`license_country` AS `license_country`,`resume`.`reference` AS `reference`,`resume`.`reference_name` AS `reference_name`,`resume`.`reference_country` AS `reference_country`,`resume`.`reference_state` AS `reference_state`,`resume`.`reference_county` AS `reference_county`,`resume`.`reference_city` AS `reference_city`,`resume`.`reference_zipcode` AS `reference_zipcode`,`resume`.`reference_address` AS `reference_address`,`resume`.`reference_phone` AS `reference_phone`,`resume`.`reference_relation` AS `reference_relation`,`resume`.`reference_years` AS `reference_years`,`resume`.`reference1` AS `reference1`,`resume`.`reference1_name` AS `reference1_name`,`resume`.`reference1_country` AS `reference1_country`,`resume`.`reference1_state` AS `reference1_state`,`resume`.`reference1_city` AS `reference1_city`,`resume`.`reference1_address` AS `reference1_address`,`resume`.`reference1_phone` AS `reference1_phone`,`resume`.`reference1_relation` AS `reference1_relation`,`resume`.`reference1_years` AS `reference1_years`,`resume`.`reference2` AS `reference2`,`resume`.`reference2_name` AS `reference2_name`,`resume`.`reference2_country` AS `reference2_country`,`resume`.`reference2_state` AS `reference2_state`,`resume`.`reference2_county` AS `reference2_county`,`resume`.`reference2_city` AS `reference2_city`,`resume`.`reference2_address` AS `reference2_address`,`resume`.`reference2_phone` AS `reference2_phone`,`resume`.`reference2_relation` AS `reference2_relation`,`resume`.`reference2_years` AS `reference2_years`,`resume`.`reference3` AS `reference3`,`resume`.`reference3_name` AS `reference3_name`,`resume`.`reference3_country` AS `reference3_country`,`resume`.`reference3_state` AS `reference3_state`,`resume`.`reference3_county` AS `reference3_county`,`resume`.`reference3_city` AS `reference3_city`,`resume`.`reference3_address` AS `reference3_address`,`resume`.`reference3_phone` AS `reference3_phone`,`resume`.`reference3_relation` AS `reference3_relation`,`resume`.`reference3_years` AS `reference3_years`,`resume`.`address1_country` AS `address1_country`,`resume`.`address1_state` AS `address1_state`,`resume`.`address1_county` AS `address1_county`,`resume`.`address1_city` AS `address1_city`,`resume`.`address1_zipcode` AS `address1_zipcode`,`resume`.`address1` AS `address1`,`resume`.`address2_country` AS `address2_country`,`resume`.`address2_state` AS `address2_state`,`resume`.`address2_county` AS `address2_county`,`resume`.`address2_city` AS `address2_city`,`resume`.`address2_zipcode` AS `address2_zipcode`,`resume`.`address2` AS `address2`,`resume`.`reference1_zipcode` AS `reference1_zipcode`,`resume`.`reference2_zipcode` AS `reference2_zipcode`,`resume`.`reference3_zipcode` AS `reference3_zipcode`,`resume`.`packageid` AS `packageid`,`resume`.`paymenthistoryid` AS `paymenthistoryid`,`resume`.`status` AS `status`,`apply`.`jobid` AS `Jobid`,`apply`.`apply_date` AS `Apply Date`,`apply`.`resumeview` AS `Resume View`,`apply`.`comments` AS `Comments` FROM (`view_resumes` `resume` JOIN `#__wrecruit_jobapply` `apply` on((`resume`.`id` = `apply`.`cvid`)));				";
				$db->setQuery( $query );
		if (!$db->queryBatch()) {
			//echo $this->_db->getErrorMsg();
			return false;
		}else return true;
	}
	function & getCountybyId($c_id)
	{
		if (is_numeric($c_id) == false) return false;
		$db = & JFactory :: getDBO();
		$query = "SELECT * FROM #__wrecruit_counties WHERE id = ".$c_id;
		$db->setQuery($query);
		$county = $db->loadObject();
		return $county;
	}

	function & getCitybyId($c_id)
	{
		if (is_numeric($c_id) == false) return false;
		$db = & JFactory :: getDBO();
		$query = "SELECT * FROM #__wrecruit_cities WHERE id = ".$c_id;
		$db->setQuery($query);
		$city = $db->loadObject();
		return $city;
	}

	function setId($id)
	{
	}
	function & getUserStatsResumes($resumeuid,$limitstart, $limit)
	{
		if (is_numeric($resumeuid) == false) return false;
		$db = & JFactory :: getDBO();
		$result = array();

		$query = 'SELECT COUNT(resume.id) FROM #__wrecruit_resume AS resume WHERE resume.uid = '.$resumeuid;

		$db->setQuery($query);
		$total= $db->loadResult();
		if ( $total <= $limitstart ) $limitstart = 0;

		//echo $query;

		$query = 'SELECT resume.id,resume.application_title,resume.first_name,resume.last_name,cat.cat_title,resume.create_date,resume.status
                    FROM #__wrecruit_resume AS resume
                    LEFT JOIN #__wrecruit_categories AS cat ON cat.id=resume.job_category
                    WHERE resume.uid = '.$resumeuid;
		$query .= ' ORDER BY resume.first_name';
		//echo $query;
		$db->setQuery($query,$limitstart, $limit);
		$result[0]= $db->loadObjectList();
		$result[1] = $total;
		return $result;
	}
	function & getWRecruitStats()
	{
		$db = & JFactory :: getDBO();
		$result = array();

		$query = 'SELECT count(id) AS totalcompanies,(SELECT count(company.id) FROM #__wrecruit_companies AS company WHERE company.status=1 ) AS activecompanies
		FROM #__wrecruit_companies ';
		$db->setQuery($query);
		$companies= $db->loadObject();

		$query = 'SELECT count(id) AS totaljobs,(SELECT count(job.id) FROM #__wrecruit_jobs AS job WHERE job.status=1 AND job.stoppublishing >= CURDATE())  AS activejobs
		FROM #__wrecruit_jobs ';
		$db->setQuery($query);
		$jobs= $db->loadObject();

		$query = 'SELECT count(id) AS totalresumes,(SELECT count(resume.id) FROM #__wrecruit_resume AS resume WHERE resume.status=1 ) AS activeresumes
		FROM #__wrecruit_resume ';
		$db->setQuery($query);
		$resumes= $db->loadObject();

		$query = "SELECT COUNT(id) AS totalfeaturedcompanies,(SELECT count(featuredcompany.id) FROM #__wrecruit_featuredcompanies  AS featuredcompany
		JOIN  #__wrecruit_employerpackages AS package ON package.id=featuredcompany.packageid
		WHERE  featuredcompany.status=1  AND DATE_ADD(featuredcompany.created,INTERVAL package.featuredcompaniesexpireindays DAY) >= CURDATE() ) AS activefeaturedcompanies
		FROM #__wrecruit_featuredcompanies ";
		$db->setQuery($query);
		$featuredcompanies= $db->loadObject();

		$query = "SELECT COUNT(id) AS totalgoldcompanies,(SELECT count(goldcompany.id) FROM #__wrecruit_goldcompanies  AS goldcompany
		JOIN  #__wrecruit_employerpackages AS package ON package.id=goldcompany.packageid
		WHERE  goldcompany.status= 1  AND DATE_ADD(goldcompany.created,INTERVAL package.goldcompaniesexpireindays DAY) >= CURDATE() )AS activegoldcompanies
		FROM #__wrecruit_goldcompanies ";
		$db->setQuery($query);
		$goldcompanies= $db->loadObject();

		$query = "SELECT COUNT(id) AS totalfeaturedjobs,(SELECT count(featuredjob.id) FROM #__wrecruit_featuredjobs AS featuredjob
		JOIN  #__wrecruit_employerpackages AS package ON package.id=featuredjob.packageid
		WHERE  featuredjob.status= 1  AND DATE_ADD(featuredjob.created,INTERVAL package.featuredjobsexpireindays DAY) >= CURDATE() ) AS activefeaturedjobs
		FROM #__wrecruit_featuredjobs ";
		$db->setQuery($query);
		$featuredjobs= $db->loadObject();

		$query = "SELECT COUNT(id) AS totalgoldjobs,(SELECT count(goldjob.id) FROM #__wrecruit_goldjobs  AS goldjob
		JOIN  #__wrecruit_employerpackages AS package ON package.id=goldjob.packageid
		WHERE  goldjob.status= 1  AND DATE_ADD(goldjob.created,INTERVAL package.goldjobsexpireindays DAY) >= CURDATE() ) AS activegoldjobs
		FROM #__wrecruit_goldjobs ";
		$db->setQuery($query);
		$goldjobs= $db->loadObject();

		$query = "SELECT COUNT(id) AS totalfeaturedresumes,(SELECT count(featuredresume.id) FROM #__wrecruit_featuredresumes  AS featuredresume
		JOIN  #__wrecruit_jobseekerpackages AS package ON package.id=featuredresume.packageid
		WHERE  featuredresume.status= 1  AND DATE_ADD(featuredresume.created,INTERVAL package.freaturedresumeexpireindays DAY) >= CURDATE() ) AS activefeaturedresumes
		FROM #__wrecruit_featuredresumes ";
		$db->setQuery($query);
		$featuredresumes= $db->loadObject();

		$query = "SELECT COUNT(id) AS totalgoldresumes,(SELECT count(goldresume.id) FROM #__wrecruit_goldresumes  AS goldresume
		JOIN  #__wrecruit_jobseekerpackages AS package ON package.id=goldresume.packageid
		WHERE  goldresume.status= 1  AND DATE_ADD(goldresume.created,INTERVAL package.goldresumeexpireindays DAY) >= CURDATE() ) AS activegoldresumes
		FROM #__wrecruit_goldresumes ";
		$db->setQuery($query);
		$goldresumes= $db->loadObject();

                $query = "SELECT COUNT(id) AS totalgoldresumes,(SELECT count(id) FROM #__wrecruit_goldresumes  WHERE status=1) AS activegoldresumes FROM #__wrecruit_goldresumes ";
		$db->setQuery($query);
		//$goldresumes= $db->loadObject();

		$query = "SELECT (SELECT SUM(paidamount) FROM jos_wrecruit_employerpaymenthistory WHERE  status=1) + (SELECT SUM(paidamount) FROM jos_wrecruit_jobseekerpaymenthistory WHERE  status=1)  AS totalpaidamount ";
		$db->setQuery($query);
		$totalpaidamount= $db->loadObject();

		$result[0]= $companies;
		$result[1]= $jobs;
		$result[2]= $resumes;
		$result[3]= $featuredcompanies;
		$result[4]= $goldcompanies;
		$result[5]= $featuredjobs;
		$result[6]= $goldjobs;
		$result[7]= $featuredresumes;
		$result[8]= $goldresumes;
		$result[9]= $totalpaidamount;
		return $result;
	}



	function & getUserFields($fieldfor, $limitstart, $limit)
	{
		if (is_numeric($fieldfor) == false) return false;
		$db = & JFactory :: getDBO();
		$result = array();

		$query = 'SELECT COUNT(id) FROM #__wrecruit_userfields WHERE fieldfor = '. $fieldfor;
		$db->setQuery($query);
		$total = $db->loadResult();
		if ( $total <= $limitstart ) $limitstart = 0;

		$query = 'SELECT field.* FROM #__wrecruit_userfields AS field WHERE fieldfor = '. $fieldfor;
		$query .= ' ORDER BY field.id';

		//echo $query;
		$db->setQuery($query,$limitstart, $limit);
		$this->_application = $db->loadObjectList();

		$result[0] = $this->_application;
		$result[1] = $total;
		return $result;
	}

	function & getFieldsOrdering($fieldfor, $limitstart, $limit)
	{
		if (is_numeric($fieldfor) == false) return false;
		$db = & JFactory :: getDBO();
		$result = array();

		$query = 'SELECT COUNT(id) FROM #__wrecruit_fieldsordering WHERE fieldfor = '. $fieldfor;
		$db->setQuery($query);
		$total = $db->loadResult();
		if ( $total <= $limitstart ) $limitstart = 0;

		$query = 'SELECT field.* ,userfield.title as userfieldtitle
					FROM #__wrecruit_fieldsordering AS field
					LEFT JOIN #__wrecruit_userfields AS userfield ON field.field = userfield.id
					WHERE field.fieldfor = '. $fieldfor;
		$query .= ' ORDER BY field.ordering';

		//echo $query;
		$db->setQuery($query,$limitstart, $limit);

		$result[0] = $db->loadObjectList();
		$result[1] = $total;
		return $result;
	}

	function &getUserFieldsforForm($fieldfor, $refid)
	{
		if (is_numeric($fieldfor) == false) return false;
		if($refid) if (is_numeric($refid) == false) return false;
		$db = &$this->getDBO();
		$field = array();
		$result = array();
		$query =  "SELECT  * FROM ".$db->nameQuote('#__wrecruit_userfields')."
					WHERE published = 1 AND fieldfor = ". $fieldfor;
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$rows = $db->loadObjectList();

		$i = 0;
		foreach ($rows as $row){
			//$result[$i] = $row;
			$field[0] = $row;
			if ($refid != ""){
				$query =  "SELECT  * FROM ".$db->nameQuote('#__wrecruit_userfield_data')." WHERE referenceid = ".$refid." AND field = ". $row->id;
				//echo '<br> SQL '.$query;
				$db->setQuery($query);
				$data = $db->loadObject();
				$field[1] = $data;
				//echo '<br> data '.$field[1];
				//$result[$i][] = $row;
			}
			if ($row->type == "select"){
				$query =  "SELECT  * FROM ".$db->nameQuote('#__wrecruit_userfieldvalues')." WHERE field = ". $row->id;
				//echo '<br> SQL '.$query;
				$db->setQuery($query);
				$values = $db->loadObjectList();
				//$result[$i] = array($values);
				$field[2] = $values;
			}
			$result[] = $field;
			$i++;
		}
		return $result;
	}

	function &getFieldsOrderingforForm($fieldfor)
	{
		if (is_numeric($fieldfor) == false) return false;
		$db = &$this->getDBO();
		$query =  "SELECT  * FROM ".$db->nameQuote('#__wrecruit_fieldsordering')."
					WHERE published = 1 AND fieldfor =  ". $fieldfor
					." ORDER BY ordering";
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$fieldordering = $db->loadObjectList();
		return $fieldordering;
	}

	function &getConfig()
	{
		if (isset($this->_config ) == false){
			$db = &$this->getDBO();

			$query = "SELECT * FROM ".$db->nameQuote('#__wrecruit_config');
			//echo '<br> SQL '.$query;
			$db->setQuery($query);
			$this->_config = $db->loadObjectList();
			foreach($this->_config as $conf)
			{
				if ($conf->configname == "defaultcountry")
					$this->_defaultcountry = $conf->configvalue;
				elseif ($conf->configname == "job_editor")
					$this->_job_editor = $conf->configvalue;
				elseif ($conf->configname == "comp_editor")
					$this->_comp_editor = $conf->configvalue;
				elseif ($conf->configname == "data_directory")
					$this->_data_directory = $conf->configvalue;
			}
		}

		return $this->_config;
	}

	function &getConfigurationsForForm()
	{
		if (isset($this->_config ) == false){
			$db = &$this->getDBO();

			$query = "SELECT * FROM ".$db->nameQuote('#__wrecruit_config');
			$db->setQuery($query);
			$this->_config = $db->loadObjectList();
		}
			foreach($this->_config as $conf)
			{
				if ($conf->configname == "defaultcountry")
					$this->_defaultcountry = $conf->configvalue;
				elseif ($conf->configname == "employer_defaultpackage")
					$employer_defaultpackage = $conf->configvalue;
				elseif ($conf->configname == "jobseeker_defaultpackage")
					$jobseeker_defaultpackage = $conf->configvalue;
				elseif ($conf->configname == "data_directory")
					$this->_data_directory = $conf->configvalue;
			}
			$countries = $this->getCountries(JText::_('JS_SELECT_COUNTRY'));
                        $employerpackages = $this->getFreeEmployerPackageForCombo(JText::_('JS_NO'));
                        $jobseekerpacakges = $this->getFreeJobSeekerPackageForCombo(JText::_('JS_NO'));
			$lists['defaultcountry'] = JHTML::_('select.genericList', $countries, 'defaultcountry', 'class="inputbox" '.'', 'value', 'text', $this->_defaultcountry);
			$lists['employer_defaultpackage'] = JHTML::_('select.genericList', $employerpackages, 'employer_defaultpackage', 'class="inputbox" '.'', 'value', 'text', $employer_defaultpackage);
			$lists['jobseeker_defaultpackage'] = JHTML::_('select.genericList', $jobseekerpacakges, 'jobseeker_defaultpackage', 'class="inputbox" '.'', 'value', 'text', $jobseeker_defaultpackage);

		$result[0] = $this->_config;
		$result[1] = $lists;
		return $result;
	}

	function & getTemplate($tempfor)
	{
		$db = & JFactory :: getDBO();
		switch($tempfor){
			case 'ew-cm' : $tempatefor = 'company-new'; break;
			case 'cm-ap' : $tempatefor = 'company-approval'; break;
			case 'cm-rj' : $tempatefor = 'company-rejecting'; break;
			case 'ew-ob' : $tempatefor = 'job-new'; break;
			case 'ob-ap' : $tempatefor = 'job-approval'; break;
			case 'ob-rj' : $tempatefor = 'job-rejecting'; break;
			case 'ew-rm' : $tempatefor = 'resume-new'; break;
			case 'rm-ap' : $tempatefor = 'resume-approval'; break;
			case 'ew-ms' : $tempatefor = 'message-email'; break;
			case 'rm-rj' : $tempatefor = 'resume-rejecting'; break;
			case 'ba-ja' : $tempatefor = 'jobapply-jobapply'; break;
			case 'ew-md' : $tempatefor = 'department-new'; break;
			case 'ew-rp' : $tempatefor = 'employer-buypackage'; break;
			case 'ew-js' : $tempatefor = 'jobseeker-buypackage'; break;
			case 'ms-sy' : $tempatefor = 'message-email'; break;
			case 'jb-at' : $tempatefor = 'job-alert'; break;
		}
		$query = "SELECT * FROM #__wrecruit_emailtemplates WHERE templatefor = ".$db->Quote($tempatefor);
		//echo $query;
		$db->setQuery($query);
		$template = $db->loadObject();
		return $template;
	}

	function & getCategorybyId($c_id)
	{
		if (is_numeric($c_id) == false) return false;
		$db = & JFactory :: getDBO();
		$query = "SELECT * FROM #__wrecruit_categories WHERE id = ".$c_id;
		//echo $query;
		$db->setQuery($query);
		$category = $db->loadObject();
		return $category;
	}

	function & getSubCategorybyId($c_id,$categoryid)
	{
		if($c_id) if (is_numeric($c_id) == false) return false;
		if($categoryid) if (is_numeric($categoryid) == false) return false;
		$db = & JFactory :: getDBO();
                if ($c_id){
                    $query = "SELECT subcategory.*,category.cat_title FROM #__wrecruit_subcategories AS subcategory
                                JOIN #__wrecruit_categories AS category ON category.id = subcategory.categoryid
                                WHERE subcategory.id = ".$c_id;
                }elseif($categoryid){
                    $query = "SELECT category.cat_title ,category.id AS categoryid FROM #__wrecruit_categories AS category WHERE category.id = ".$categoryid;
                }
		//echo $query;
		$db->setQuery($query);
		$subcategory = $db->loadObject();
		return $subcategory;
	}

	function & getJobTypebyId($c_id)
	{
		if (is_numeric($c_id) == false) return false;
		$db = & JFactory :: getDBO();
		$query = "SELECT * FROM #__wrecruit_jobtypes WHERE id = ".$c_id;
		//echo $query;
		$db->setQuery($query);
		$jobtype = $db->loadObject();
		return $jobtype;
	}
	function & getJobAgesbyId($c_id)
	{
		if (is_numeric($c_id) == false) return false;
		$db = & JFactory :: getDBO();
		$query = "SELECT * FROM #__wrecruit_ages WHERE id = ".$c_id;
		//echo $query;
		$db->setQuery($query);
		$ages = $db->loadObject();
		return $ages;
	}
	function & getCurrencybyId($c_id)
	{
		if (is_numeric($c_id) == false) return false;
		$db = & JFactory :: getDBO();
		$query = "SELECT * FROM #__wrecruit_currencies WHERE id = ".$c_id;
		//echo $query;
		$db->setQuery($query);
		$currency = $db->loadObject();
		return $currency;
	}
	function & getJobCareerLevelbyId($c_id)
	{
		if (is_numeric($c_id) == false) return false;
		$db = & JFactory :: getDBO();
		$query = "SELECT * FROM #__wrecruit_careerlevels WHERE id = ".$c_id;
		//echo $query;
		$db->setQuery($query);
		$career= $db->loadObject();
		return $career;
	}
	function & getJobExperiencebyId($c_id)
	{
		if (is_numeric($c_id) == false) return false;
		$db = & JFactory :: getDBO();
		$query = "SELECT * FROM #__wrecruit_experiences WHERE id = ".$c_id;
		//echo $query;
		$db->setQuery($query);
		$experience = $db->loadObject();
		return $experience;
	}
	function & getSalaryRangeTypebyId($c_id)
	{
		if (is_numeric($c_id) == false) return false;
		$db = & JFactory :: getDBO();
		$query = "SELECT * FROM #__wrecruit_salaryrangetypes WHERE id = ".$c_id;
		//echo $query;
		$db->setQuery($query);
		$jobtype = $db->loadObject();
		return $jobtype;
	}

	function & getJobStatusbyId($c_id)
	{
		if (is_numeric($c_id) == false) return false;
		$db = & JFactory :: getDBO();
		$query = "SELECT * FROM #__wrecruit_jobstatus WHERE id = ".$c_id;
		//echo $query;
		$db->setQuery($query);
		$jobstatus = $db->loadObject();
		return $jobstatus;
	}

	function & getShiftbyId($c_id)
	{
		if (is_numeric($c_id) == false) return false;
		$db = & JFactory :: getDBO();
		$query = "SELECT * FROM #__wrecruit_shifts WHERE id = ".$c_id;
		//echo $query;
		$db->setQuery($query);
		$shift = $db->loadObject();
		return $shift;
	}
	function & getMessagesbyId($id)
	{
        	//function & getMessagesbyId($id,$jobid ,$resumeid)
		if (is_numeric($id) == false) return false;
		$db = & JFactory :: getDBO();

		$query = "SELECT * FROM #__wrecruit_messages WHERE id = ".$id;
		$db->setQuery($query);
		//echo $query;
                $message = $db->loadObject();
                $status = array(
                '0' => array('value' => 0,'text' => JText::_('JS_PENDDING')),
                '1' => array('value' => 1,'text' => JText::_('JS_APPROVE')),
                '2' => array('value' => -1,'text' => JText::_('JS_REJECT')),);
                $lists['status'] = JHTML::_('select.genericList', $status, 'status', 'class="inputbox required" '. '', 'value', 'text', $message->status);

                $result[0] = $message;
                $result[1] = $lists;
                return $result;
	}

	function &getMessagesbyJobResume($uid,$jobid,$resumeid,$limit,$limitstart)
	{
                $result = array();
		$db = &$this->getDBO();
		if (is_numeric($uid) == false) return false;
		if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		if (is_numeric($jobid) == false) return false;
		if (is_numeric($resumeid) == false) return false;
		$listjobconfig = $this->getConfigByFor('listjob');
		$query = "SELECT count(message.id)
                        FROM ".$db->nameQuote('#__wrecruit_messages')." AS message
                        WHERE message.status = 1 AND message.jobid =".$jobid." AND message.resumeid = ".$resumeid;
		$db->setQuery($query);
		$total = $db->loadResult();
		if ( $total <= $limitstart ) $limitstart = 0;

                $query = "SELECT message.*, job.title, resume.application_title, resume.first_name, resume.middle_name, resume.last_name
                        FROM ".$db->nameQuote('#__wrecruit_messages')." AS message
                                JOIN ".$db->nameQuote('#__wrecruit_jobs')." AS job ON job.id = message.jobid
				JOIN ".$db->nameQuote('#__wrecruit_resume')." AS resume ON resume.id = message.resumeid
                        WHERE message.status = 1 AND message.jobid =".$jobid." AND message.resumeid = ".$resumeid." ORDER BY  message.created DESC";
                //echo $query;
		$db->setQuery($query, $limitstart, $limit);
		$messages = $db->loadObjectList();
                    $query = "SELECT job.id as jobid, job.uid as employerid, job.title, resume.id as resumeid, resume.uid as jobseekerid, resume.application_title, resume.first_name, resume.middle_name, resume.last_name
                                    FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job
                                    JOIN ".$db->nameQuote('#__wrecruit_resume')." AS resume ON resume.id = ".$resumeid."
                                    WHERE job.id = ".$jobid;
               // echo $query;
                    $db->setQuery($query);
                    $summary = $db->loadObject();
		$result[0] = $messages;
		$result[1] = $total;
                $result[3] = $summary;

		return $result;
	}
	function &getMessagesbyJobResumes($uid,$jobid,$resumeid)
	{
		$result = array();
		$db = &$this->getDBO();
		if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		if (is_numeric($jobid) == false) return false;
		if (is_numeric($resumeid) == false) return false;
                $status = array(
                '0' => array('value' => 0,'text' => JText::_('JS_PENDDING')),
                '1' => array('value' => 1,'text' => JText::_('JS_APPROVE')),
                '2' => array('value' => -1,'text' => JText::_('JS_REJECT')),);
                $lists['status'] = JHTML::_('select.genericList', $status, 'status', 'class="inputbox required" '. '', 'value', 'text', $message->status);
                $query = "SELECT message.*, job.title, resume.application_title, resume.first_name, resume.middle_name, resume.last_name
                        FROM ".$db->nameQuote('#__wrecruit_messages')." AS message
                                JOIN ".$db->nameQuote('#__wrecruit_jobs')." AS job ON job.id = message.jobid
				JOIN ".$db->nameQuote('#__wrecruit_resume')." AS resume ON resume.id = message.resumeid
                        WHERE message.status = 1 AND message.jobid =".$jobid." AND message.resumeid = ".$resumeid." ORDER BY  message.created DESC";
                //echo $query;
		$db->setQuery($query, $limitstart, $limit);
		$messages = $db->loadObjectList();
                    $query = "SELECT job.id as jobid, job.uid as employerid, job.title, resume.id as resumeid, resume.uid as jobseekerid, resume.application_title, resume.first_name, resume.middle_name, resume.last_name
                                    FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job
                                    JOIN ".$db->nameQuote('#__wrecruit_resume')." AS resume ON resume.id = ".$resumeid."
                                    WHERE job.id = ".$jobid;
                //echo $query;
                    $db->setQuery($query);
                    $summary = $db->loadObject();
		$result[0] = $messages;
                $result[1] = $summary;
                $result[2] = $lists;

		return $result;
	}
	function & getHighestEducationbyId($c_id)
	{
		if (is_numeric($c_id) == false) return false;
		$db = & JFactory :: getDBO();
		$query = "SELECT * FROM #__wrecruit_heighesteducation WHERE id = ".$c_id;
		//echo $query;
		$db->setQuery($query);
		$education = $db->loadObject();
		return $education;
	}

/* zain */
        function & getFolderbyId($c_id)
	{
		if (is_numeric($c_id) == false) return false;
		$db = & JFactory :: getDBO();
		$query = "SELECT * FROM #__wrecruit_folders WHERE id = ".$c_id;
		//echo $query;
                $db->setQuery($query);
		$folders = $db->loadObject();
                $result[0] = $folders ;
                $lists = '';
                $status = array(
                '0' => array('value' => 0,'text' => JText::_('JS_PENDDING')),
                '1' => array('value' => 1,'text' => JText::_('JS_APPROVE')),
                '2' => array('value' => -1,'text' => JText::_('JS_REJECT')),);
                if(isset($folders))$lists['status'] = JHTML::_('select.genericList', $status, 'status', 'class="inputbox required" '. '', 'value', 'text', $folders->status);
                $result[1] = $lists;
                return $result;

	}

	function & getCompanybyId($c_id)
	{
		if (is_numeric($c_id) == false) return false;
		$db = & JFactory :: getDBO();
		$query = "SELECT * FROM #__wrecruit_companies WHERE id = ".$c_id;
		//echo $query;
		$db->setQuery($query);
		$company = $db->loadObject();

		$status = array(
			'0' => array('value' => 0,'text' => JText::_('JS_PENDDING')),
			'1' => array('value' => 1,'text' => JText::_('JS_APPROVE')),
			'2' => array('value' => -1,'text' => JText::_('JS_REJECT')),);

		$countries = $this->getCountries('');


		if ( isset($company) ){
			if(isset($company))$states = $this->getStates($company->country);
			if(isset($company))$counties = $this->getCounties($company->state);
			if(isset($company))$cities = $this->getCities($company->county);
			$lists['category'] = JHTML::_('select.genericList', $this->getCategories('',''), 'category', 'class="inputbox required" '. '', 'value', 'text', $company->category);
			$lists['country'] = JHTML::_('select.genericList', $countries, 'country','class="inputbox required" '.'onChange="dochange(\'state\', this.value)"', 'value', 'text', $company->country);
			if ( isset($states[1]) ) if ($states[1] != '')$lists['state'] = JHTML::_('select.genericList', $states, 'state', 'class="inputbox" '. 'onChange="dochange(\'county\', this.value)"', 'value', 'text', $company->state);
			if ( isset($counties[1]) ) if ($counties[1] != '')$lists['county'] = JHTML::_('select.genericList', $counties, 'county', 'class="inputbox" '. 'onChange="dochange(\'city\', this.value)"', 'value', 'text', $company->county);
			if ( isset($cities[1]) ) if ($cities[1] != '')$lists['city'] = JHTML::_('select.genericList', $cities, 'city', 'class="inputbox" '. '', 'value', 'text', $company->city);
			$lists['status'] = JHTML::_('select.genericList', $status, 'status', 'class="inputbox required" '. '', 'value', 'text', $company->status);
		}else{
			if(! isset($this->_config)){
				$this->getConfig();
			}
			if(isset($this->_defaultcountry))$states = $this->getStates($this->_defaultcountry);
			$lists['category'] = JHTML::_('select.genericList', $this->getCategories('',''), 'category', 'class="inputbox required" '. '', 'value', 'text', '');
//			$lists['companies'] = JHTML::_('select.genericList', $this->getCompanies($uid), 'company', 'class="inputbox required" '. '', 'value', 'text', '');
			$lists['country'] = JHTML::_('select.genericList', $countries, 'country','class="inputbox required" '.'onChange="dochange(\'state\', this.value)"', 'value', 'text', $this->_defaultcountry);
			if ( isset($states[1]) ) if ($states[1] != '')$lists['state'] = JHTML::_('select.genericList', $states, 'state', 'class="inputbox" '. 'onChange="dochange(\'county\', this.value)"', 'value', 'text', '');
			if ( isset($counties[1]) ) if ($counties[1] != '')$lists['county'] = JHTML::_('select.genericList', $counties, 'county', 'class="inputbox" '. 'onChange="dochange(\'city\', this.value)"', 'value', 'text', '');
			if ( isset($cities[1]) ) if ($cities[1] != '')$lists['city'] = JHTML::_('select.genericList', $cities, 'city', 'class="inputbox" '. '', 'value', 'text', '');
			$lists['status'] = JHTML::_('select.genericList', $status, 'status', 'class="inputbox required" '. '', 'value', 'text', '');
		}
		//$fieldordering = $this->getFieldsOrdering(1);// company fields
		//$userfields = $this->getUserFields(1, 0, 99999); // company fields, id
		$result[0] = $company;
		$result[1] = $lists;
		$result[2] = $this->getUserFieldsforForm(1, $c_id); // company fields, id
		$result[3] = $this->getFieldsOrderingforForm(1);// company fields

		return $result;

	}
	function & getJobSeekerPackagebyId($c_id)
	{
		if (is_numeric($c_id) == false) return false;
		$db = & JFactory :: getDBO();
		$query = "SELECT * FROM #__wrecruit_jobseekerpackages WHERE id = ".$c_id;
		$db->setQuery($query);
		$package = $db->loadObject();
		$status = array(
			'0' => array('value' => 0,'text' => JText::_('JS_UNPUBLISHED')),
			'1' => array('value' => 1,'text' => JText::_('JS_PUBLISHED')),);
		$type = array(
			'0' => array('value' => 1,'text' => JText::_('Amount')),
			'1' => array('value' => 2,'text' => JText::_('%')),);
		$yesNo = array(
			'0' => array('value' => 1,'text' => JText::_('yes')),
			'1' => array('value' => 0,'text' => JText::_('No')),);

		if ( isset($package) ){
			$lists['status'] = JHTML::_('select.genericList', $status, 'status', 'class="inputbox required" '. '', 'value', 'text', $package->status);
			$lists['type'] = JHTML::_('select.genericList', $type, 'discounttype', 'class="inputbox required" '. '', 'value', 'text', $package->discounttype);
			$lists['jobsearch'] = JHTML::_('select.genericList', $yesNo, 'jobsearch', 'class="inputbox required" '. '', 'value', 'text', $package->jobsearch);
			$lists['savejobsearch'] = JHTML::_('select.genericList', $yesNo, 'savejobsearch', 'class="inputbox required" '. '', 'value', 'text', $package->savejobsearch);
			$lists['jobalertsetting'] = JHTML::_('select.genericList', $yesNo, 'jobalertsetting', 'class="inputbox required" '. '', 'value', 'text', $package->jobalertsetting);

		}else{
			$lists['status'] = JHTML::_('select.genericList', $status, 'status', 'class="inputbox required" '. '', 'value', 'text', '');
			$lists['type'] = JHTML::_('select.genericList', $type, 'discounttype', 'class="inputbox required" '. '', 'value', 'text', '');
			$lists['jobsearch'] = JHTML::_('select.genericList', $yesNo, 'jobsearch', 'class="inputbox required" '. '', 'value', 'text', '');
			$lists['savejobsearch'] = JHTML::_('select.genericList', $yesNo, 'savejobsearch', 'class="inputbox required" '. '', 'value', 'text', '');
			$lists['jobalertsetting'] = JHTML::_('select.genericList', $yesNo, 'jobalertsetting', 'class="inputbox required" '. '', 'value', 'text', '');



        	}

		$result[0]=$package;
		$result[1]=$lists;
                $result[2]=$this->getConfigByFor('payment');

		return $result;

	}

        function getDepartmentsByCompanyId( $companyid, $title ){
		if($companyid) if (is_numeric($companyid) == false) return false;
		$db =& JFactory::getDBO();
                $departments = array();
		if ($companyid){
			$query = "SELECT id, name FROM ".$db->nameQuote('#__wrecruit_departments')." WHERE status = 1 AND companyid = ".$companyid." ORDER BY name ASC ";
			$db->setQuery( $query );
			$rows = $db->loadObjectList();
			if ($db->getErrorNum()) {
				echo $db->stderr();
				return false;
			}

			if($title)
				$departments[] =  array('value' => JText::_(''),'text' => $title);
			foreach($rows as $row)	{
				$departments[] =  array('value' => $row->id,	'text' => $row->name);
			}
		}
		return $departments;
	}
	function & getJobbyId($c_id, $uid)
	{
		if($uid) if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		if (is_numeric($c_id) == false) return false;
		$db = & JFactory :: getDBO();

		$query = "SELECT job.*, cat.cat_title, salary.rangestart, salary.rangeend
			FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job
			JOIN ".$db->nameQuote('#__wrecruit_categories')." AS cat ON job.jobcategory = cat.id
			LEFT JOIN ".$db->nameQuote('#__wrecruit_salaryrange')." AS salary ON job.jobsalaryrange = salary.id
			LEFT JOIN ".$db->nameQuote('#__wrecruit_currencies')." AS currency ON currency.id = job.currencyid 
			WHERE job.id = ".$c_id;

		$db->setQuery($query);
		$this->_job = $db->loadObject();

		$status = array(
			'0' => array('value' => 0,'text' => JText::_('JS_PENDDING')),
			'1' => array('value' => 1,'text' => JText::_('JS_APPROVE')),
			'2' => array('value' => -1,'text' => JText::_('JS_REJECT')),);
		$countries = $this->getCountries('');
		$companies = $this->getCompanies($uid);
		$departments =$this->getDepartment($uid) ;
                $categories = $this->getCategories('','');

		if ( isset($this->_job) ){
			$states = $this->getStates($this->_job->country);
			$counties = $this->getCounties($this->_job->state);
			$cities = $this->getCities($this->_job->county);
			$lists['companies'] = JHTML::_('select.genericList', $companies , 'companyid', 'class="inputbox required" '. '', 'value', 'text', $this->_job->companyid);
			$lists['departments'] = JHTML::_('select.genericList', $this->getDepartmentsByCompanyId($this->_job->companyid,'') , 'departmentid', 'class="inputbox" '. '', 'value', 'text', $this->_job->departmentid);
			$lists['jobcategory'] = JHTML::_('select.genericList', $categories, 'jobcategory', 'class="inputbox" '. 'onChange="fj_getsubcategories(\'fj_subcategory\', this.value)"', 'value', 'text', $this->_job->jobcategory);
			$lists['subcategory'] = JHTML::_('select.genericList', $this->getSubCategoriesforCombo($this->_job->jobcategory,JText::_('JS_SUB_CATEGORY'),''), 'subcategoryid', 'class="inputbox" '. '', 'value', 'text', $this->_job->subcategoryid);
			$lists['jobtype'] = JHTML::_('select.genericList', $this->getJobType(''), 'jobtype', 'class="inputbox" '. '', 'value', 'text', $this->_job->jobtype);
			$lists['jobstatus'] = JHTML::_('select.genericList', $this->getJobStatus(''), 'jobstatus', 'class="inputbox required" '. '', 'value', 'text', $this->_job->jobstatus);
			$lists['educationminimax'] = JHTML::_('select.genericList', $this->getMiniMax(''), 'educationminimax', 'class="inputbox" '. '', 'value', 'text', $this->_job->educationminimax);
			$lists['education'] = JHTML::_('select.genericList', $this->getHeighestEducation(''), 'educationid', 'class="inputbox" '. '', 'value', 'text', $this->_job->educationid);
			$lists['minimumeducationrange'] = JHTML::_('select.genericList', $this->getHeighestEducation(JText::_('JS_MINIMUM')), 'mineducationrange', 'class="inputbox" '. '', 'value', 'text', $this->_job->mineducationrange);
			$lists['maximumeducationrange'] = JHTML::_('select.genericList', $this->getHeighestEducation(JText::_('JS_MAXIMUM')), 'maxeducationrange', 'class="inputbox" '. '', 'value', 'text', $this->_job->maxeducationrange);

			$lists['shift'] = JHTML::_('select.genericList', $this->getShift(''), 'shift', 'class="inputbox" '. '', 'value', 'text', $this->_job->shift);
			$lists['salaryrangefrom'] = JHTML::_('select.genericList', $this->getSalaryRange(JText::_('JS_FROM')), 'salaryrangefrom', 'class="inputbox" '. '', 'value', 'text', $this->_job->salaryrangefrom);
			$lists['salaryrangeto'] = JHTML::_('select.genericList', $this->getSalaryRange(JText::_('JS_TO')), 'salaryrangeto', 'class="inputbox" '. '', 'value', 'text', $this->_job->salaryrangeto);
			$lists['salaryrangetypes'] = JHTML::_('select.genericList', $this->getSalaryRangeTypes(''), 'salaryrangetype', 'class="inputbox" '. '', 'value', 'text', $this->_job->salaryrangetype);

			$lists['experienceminimax'] = JHTML::_('select.genericList', $this->getMiniMax(''), 'experienceminimax', 'class="inputbox" '. '', 'value', 'text', $this->_job->experienceminimax);
			$lists['experience'] = JHTML::_('select.genericList', $this->getExperiences(JText::_('JS_SELECT')), 'experienceid', 'class="inputbox" '. '', 'value', 'text', $this->_job->experienceid);
			$lists['minimumexperiencerange'] = JHTML::_('select.genericList', $this->getExperiences(JText::_('JS_MINIMUM')), 'minexperiencerange', 'class="inputbox" '. '', 'value', 'text', $this->_job->minexperiencerange);
			$lists['maximumexperiencerange'] = JHTML::_('select.genericList', $this->getExperiences(JText::_('JS_MAXIMUM')), 'maxexperiencerange', 'class="inputbox" '. '', 'value', 'text', $this->_job->maxexperiencerange);
			$lists['country'] = JHTML::_('select.genericList', $countries, 'country','class="inputbox required" '.'onChange="dochange(\'state\', this.value)"', 'value', 'text', $this->_job->country);
			if ( isset($states[1]) ) if ($states[1] != '')$lists['state'] = JHTML::_('select.genericList', $states, 'state', 'class="inputbox" '. 'onChange="dochange(\'county\', this.value)"', 'value', 'text', $this->_job->state);
			if ( isset($counties[1]) ) if ($counties[1] != '')$lists['county'] = JHTML::_('select.genericList', $counties, 'county', 'class="inputbox" '. 'onChange="dochange(\'city\', this.value)"', 'value', 'text', $this->_job->county);
			if ( isset($cities[1]) ) if ($cities[1] != '')$lists['city'] = JHTML::_('select.genericList', $cities, 'city', 'class="inputbox" '. '', 'value', 'text', $this->_job->city);

			$lists['agefrom'] = JHTML::_('select.genericList', $this->getAges(JText::_('JS_FROM')), 'agefrom', 'class="inputbox" '. '', 'value', 'text', $this->_job->agefrom);
			$lists['ageto'] = JHTML::_('select.genericList', $this->getAges(JText::_('JS_TO')), 'ageto', 'class="inputbox" '. '', 'value', 'text', $this->_job->ageto);

			$lists['gender'] = JHTML::_('select.genericList', $this->getGender(JText::_('JS_DOES_NOT_MATTER')), 'gender', 'class="inputbox " '. '', 'value', 'text', $this->_job->gender);

			$lists['careerlevel'] = JHTML::_('select.genericList', $this->getCareerLevels(JText::_('JS_SELECT')), 'careerlevel', 'class="inputbox" '. '', 'value', 'text', $this->_job->careerlevel);
			$lists['workpermit'] = JHTML::_('select.genericList', $this->getCountries(JText::_('JS_SELECT')), 'workpermit', 'class="inputbox" '. '', 'value', 'text', $this->_job->workpermit);
			$lists['requiredtravel'] = JHTML::_('select.genericList', $this->getRequiredTravel(JText::_('JS_SELECT')), 'requiredtravel', 'class="inputbox" '. '', 'value', 'text', $this->_job->requiredtravel);

			$lists['status'] = JHTML::_('select.genericList', $status, 'status', 'class="inputbox required" '. '', 'value', 'text', $this->_job->status);
			$lists['sendemail'] = JHTML::_('select.genericList', $this->getSendEmail(), 'sendemail', 'class="inputbox" '. '', 'value', 'text', $this->_job->sendemail);
		    $lists['currencyid'] = JHTML::_('select.genericList', $this->getCurrency(), 'currencyid', 'class="inputbox required" '. '', 'value', 'text', $this->_job->currencyid);
		}else{
			if(! isset($this->_config)){ $this->getConfig();}
			if(isset($this->_defaultcountry))$states = $this->getStates($this->_defaultcountry);
			$lists['companies'] = JHTML::_('select.genericList', $companies, 'companyid', 'class="inputbox required" '.'onChange="getdepartments(\'department\', this.value)"'. '', 'value', 'text', '');
            if(isset($company[0]['value']))  $lists['departments'] = JHTML::_('select.genericList', $this->getDepartmentsByCompanyId($companies[0]['value'],'') , 'departmentid', 'class="inputbox" '. '', 'value', 'text', '');
			$lists['jobcategory'] = JHTML::_('select.genericList', $categories, 'jobcategory', 'class="inputbox" '. 'onChange="fj_getsubcategories(\'fj_subcategory\', this.value)"', 'value', 'text', '');
			$lists['subcategory'] = JHTML::_('select.genericList', $this->getSubCategoriesforCombo($categories[0]['value'],JText::_('JS_SUB_CATEGORY'),''), 'subcategoryid', 'class="inputbox" '. '', 'value', 'text', '');
			$lists['jobtype'] = JHTML::_('select.genericList', $this->getJobType(''), 'jobtype', 'class="inputbox" '. '', 'value', 'text', '');
			$lists['jobstatus'] = JHTML::_('select.genericList', $this->getJobStatus(''), 'jobstatus', 'class="inputbox required" '. '', 'value', 'text', '');

			$lists['educationminimax'] = JHTML::_('select.genericList', $this->getMiniMax(''), 'educationminimax', 'class="inputbox" '. '', 'value', 'text', '');
			$lists['education'] = JHTML::_('select.genericList', $this->getHeighestEducation(''), 'educationid', 'class="inputbox" '. '', 'value', 'text', '');
			$lists['minimumeducationrange'] = JHTML::_('select.genericList', $this->getHeighestEducation(JText::_('JS_MINIMUM')), 'mineducationrange', 'class="inputbox" '. '', 'value', 'text', '');
			$lists['maximumeducationrange'] = JHTML::_('select.genericList', $this->getHeighestEducation(JText::_('JS_MAXIMUM')), 'maxeducationrange', 'class="inputbox" '. '', 'value', 'text', '');
			$lists['shift'] = JHTML::_('select.genericList', $this->getShift(''), 'shift', 'class="inputbox" '. '', 'value', 'text', '');

			$lists['salaryrangefrom'] = JHTML::_('select.genericList', $this->getSalaryRange(JText::_('JS_FROM')), 'salaryrangefrom', 'class="inputbox" '. '', 'value', 'text', '');
			$lists['salaryrangeto'] = JHTML::_('select.genericList', $this->getSalaryRange(JText::_('JS_TO')), 'salaryrangeto', 'class="inputbox" '. '', 'value', 'text', '');
			$lists['salaryrangetypes'] = JHTML::_('select.genericList', $this->getSalaryRangeTypes(''), 'salaryrangetype', 'class="inputbox" '. '', 'value', 'text', '2');


			$lists['experienceminimax'] = JHTML::_('select.genericList', $this->getMiniMax(''), 'experienceminimax', 'class="inputbox" '. '', 'value', 'text', '');
			$lists['experience'] = JHTML::_('select.genericList', $this->getExperiences(JText::_('JS_SELECT')), 'experienceid', 'class="inputbox" '. '', 'value', 'text', '');
			$lists['minimumexperiencerange'] = JHTML::_('select.genericList', $this->getExperiences(JText::_('JS_MINIMUM')), 'minexperiencerange', 'class="inputbox" '. '', 'value', 'text', '');
			$lists['maximumexperiencerange'] = JHTML::_('select.genericList', $this->getExperiences(JText::_('JS_MAXIMUM')), 'maxexperiencerange', 'class="inputbox" '. '', 'value', 'text', '');



			$lists['country'] = JHTML::_('select.genericList', $countries, 'country','class="inputbox required" '.'onChange="dochange(\'state\', this.value)"', 'value', 'text', $this->_defaultcountry);
			if ( isset($states[1]) ) if ($states[1] != '')$lists['state'] = JHTML::_('select.genericList', $states, 'state', 'class="inputbox" '. 'onChange="dochange(\'county\', this.value)"', 'value', 'text', '');
			if ( isset($counties[1]) ) if ($counties[1] != '')$lists['county'] = JHTML::_('select.genericList', $counties, 'county', 'class="inputbox" '. 'onChange="dochange(\'city\', this.value)"', 'value', 'text', '');
			if ( isset($cities[1]) ) if ($cities[1] != '')$lists['city'] = JHTML::_('select.genericList', $cities, 'city', 'class="inputbox" '. '', 'value', 'text', '');

			$lists['agefrom'] = JHTML::_('select.genericList', $this->getAges(JText::_('JS_FROM')), 'agefrom', 'class="inputbox" '. '', 'value', 'text', '');
			$lists['ageto'] = JHTML::_('select.genericList', $this->getAges(JText::_('JS_TO')), 'ageto', 'class="inputbox" '. '', 'value', 'text', '');

			$lists['gender'] = JHTML::_('select.genericList', $this->getGender(JText::_('JS_DOES_NOT_MATTER')), 'gender', 'class="inputbox" '. '', 'value', 'text', '');
		 	$lists['careerlevel'] = JHTML::_('select.genericList', $this->getCareerLevels(JText::_('JS_SELECT')), 'careerlevel', 'class="inputbox" '. '', 'value', 'text', '');
			$lists['workpermit'] = JHTML::_('select.genericList', $this->getCountries(JText::_('JS_SELECT')), 'workpermit', 'class="inputbox" '. '', 'value', 'text', $this->_defaultcountry);
			$lists['requiredtravel'] = JHTML::_('select.genericList', $this->getRequiredTravel(JText::_('JS_SELECT')), 'requiredtravel', 'class="inputbox" '. '', 'value', 'text', '');

            $lists['status'] = JHTML::_('select.genericList', $status, 'status', 'class="inputbox required" '. '', 'value', 'text', '');
			$lists['sendemail'] = JHTML::_('select.genericList', $this->getSendEmail(), 'sendemail', 'class="inputbox" '. '', 'value', 'text', '$this->_job->sendemail','');
		    $lists['currencyid'] = JHTML::_('select.genericList', $this->getCurrency(), 'currencyid', 'class="inputbox required" '. '', 'value', 'text', '');
 
		}

		$result[0] = $this->_job;
		$result[1] = $lists;
		$result[2] = $this->getUserFieldsforForm(2, $c_id); // job fields, refid
		$result[3] = $this->getFieldsOrderingforForm(2); // job fields

		return $result;
	}
	
	function &getCurrency(){
		
		$db = & JFactory :: getDBO();
		if(! isset($this->_defaultcurrency)) $this->_defaultcurrency = $this->getDefaultCurrency();
		$q = "SELECT * FROM ".$db->nameQuote('#__wrecruit_currencies')." WHERE status = 1 AND id = " .$this->_defaultcurrency ;
		//echo $q;
		$db->setQuery($q);
		$defaultcurrency = $db->loadObject();
		$combobox=array();
		if(count($defaultcurrency)){
			$combobox[] =  array('value' => $defaultcurrency->id,'text' => JText::_($defaultcurrency->symbol));
		}
		if(empty($defaultcurrency->id)){
			$defaultcurrency->id = -1;
		}

		$q = "SELECT * FROM ".$db->nameQuote('#__wrecruit_currencies')." WHERE status = 1 AND id != ".$defaultcurrency->id ;
		$db->setQuery($q);
		$allcurrency = $db->loadObjectList();
		foreach($allcurrency as $currency){
			$combobox[] =  array('value' => $currency->id,'text' => JText::_($currency->symbol));		
		}

		return $combobox;
	}
	function getDefaultCurrency(){
		$db = & JFactory :: getDBO();
		$q = "SELECT id FROM ".$db->nameQuote('#__wrecruit_currencies')." AS id WHERE id.default = 1";
		$db->setQuery($q);
		$defaultValue = $db->loadResult();
		if(!$defaultValue){ 
			$q = "SELECT id FROM " .$db->nameQuote('#__wrecruit_currencies') ;
			$db->setQuery($q);
			$defaultValue = $db->loadResult();
		}
		return $defaultValue;
		
	}
	

        	function & getEmpAppbyId($c_id)
	{
		if (is_numeric($c_id) == false) return false;
		$db = & JFactory :: getDBO();
		$query = "SELECT * FROM #__wrecruit_resume WHERE id = ".$c_id;
		//echo $query;
		$db->setQuery($query);
		$this->_application = $db->loadObject();
		$result[0] = $this->_application;
		//$result[2] = $this->getUserFields(3, this->_application->id); // company fields, id  USER FIELD NOT FOR RESUME
		$result[3] = $this->getFieldsOrderingforForm(3); // resume fields
		return $result;
	}

	function & getSalaryRangebyId($c_id)
	{
		if (is_numeric($c_id) == false) return false;
		$db = & JFactory :: getDBO();
		$query = "SELECT * FROM #__wrecruit_salaryrange WHERE id = ".$c_id;
		//echo $query;
		$db->setQuery($query);
		$this->_application = $db->loadObject();
		return $this->_application;
	}

	function & getRolebyId($c_id)
	{
		if (is_numeric($c_id) == false) return false;
		$db = & JFactory :: getDBO();
		$query = "SELECT * FROM #__wrecruit_roles WHERE id = ".$c_id;
		//echo $query;
		$db->setQuery($query);
		$role = $db->loadObject();
		$for = array(
			'0' => array('value' => 1,'text' => JText::_('JS_EMPLOYER')),
			'1' => array('value' => 2,'text' => JText::_('JS_JOB_SEEKER')),);

		if ( isset($role) ){
			$lists['rolefor'] = JHTML::_('select.genericList', $for, 'rolefor', 'class="inputbox required" '. '', 'value', 'text', $role->rolefor);
		}else{
			$lists['rolefor'] = JHTML::_('select.genericList', $for, 'rolefor', 'class="inputbox required" '. '', 'value', 'text', '');
		}
		$result[0] = $role;
		$result[1] = $lists;
		return $result;
	}

	function & getChangeRolebyId($c_id)
	{
		if (is_numeric($c_id) == false) return false;
		$version = new JVersion;
		$joomla = $version->getShortVersion();
		$jversion = '1.5';
                if(substr($joomla,0,3) == '1.6') $jversion = '1.6';
                elseif(substr($joomla,0,3) == '1.7') $jversion = '1.7';
		$db = & JFactory :: getDBO();
		if ($jversion == '1.5'){
			$query = 'SELECT a.*, g.name AS groupname, usr.id AS userroleid, usr.role,
                                    role.title AS roletitle , usr.dated AS dated'
				. ' FROM #__users AS a'
				. ' INNER JOIN #__core_acl_aro AS aro ON aro.value = a.id'
				. ' INNER JOIN #__core_acl_groups_aro_map AS gm ON gm.aro_id = aro.id'
				. ' INNER JOIN #__core_acl_aro_groups AS g ON g.id = gm.group_id'
				. ' LEFT JOIN #__wrecruit_userroles AS usr ON usr.uid = a.id '
				. ' LEFT JOIN #__wrecruit_roles AS role ON role.id = usr.role'
				. ' WHERE a.id = '	.$c_id;

			//echo $query;
			$db->setQuery($query);
			$user = $db->loadObject();
		}else if ( ($jversion == '1.6') OR ($jversion == '1.7') ){
			$query = 'SELECT a.*, g.title AS groupname, usr.id AS userroleid, usr.role, 
                            role.title AS roletitle,usr.dated AS dated'
			. ' FROM #__users AS a'
			. ' INNER JOIN #__user_usergroup_map AS aro ON aro.user_id = a.id'
			. ' INNER JOIN #__usergroups AS g ON g.id = aro.group_id'
			. ' LEFT JOIN #__wrecruit_userroles AS usr ON usr.uid = a.id '
			. ' LEFT JOIN #__wrecruit_roles AS role ON role.id = usr.role'
			. ' WHERE a.id = '.$c_id;

			//echo $query;
			$db->setQuery($query);
			$user = $db->loadObject();
		}
		$roles = $this->getRoles('');
		if ( isset($user) ){
			$lists['roles'] = JHTML::_('select.genericList', $roles, 'role', 'class="inputbox required" '. '', 'value', 'text', $user->role);
		}else{
			$lists['roles'] = JHTML::_('select.genericList', $roles, 'role', 'class="inputbox required" '. '', 'value', 'text', '');
		}
		$result[0] = $user;
		$result[1] = $lists;
		return $result;
	}

	function & getUserFieldbyId($c_id)
	{
		if (is_numeric($c_id) == false) return false;
		$result = array();
		$db = & JFactory :: getDBO();
		$query = "SELECT * FROM #__wrecruit_userfields WHERE id = ".$db->Quote($c_id);
		//echo $query;
		$db->setQuery($query);
		$result[0] = $db->loadObject();

		$query = "SELECT * FROM #__wrecruit_userfieldvalues WHERE field = ".$db->Quote($c_id);
		//echo $query;
		$db->setQuery($query);
		$result[1] = $db->loadObjectList();

		return $result;
	}

	function & getResumeUserFields()
	{
		$result = array();
		$db = & JFactory :: getDBO();
		$query = "SELECT * FROM #__wrecruit_fieldsordering 
					WHERE fieldfor = 3 
					AND (field = 'section_userfields' OR field = 'userfield1' OR field = 'userfield2'
					OR field = 'userfield3' OR field = 'userfield4' OR field = 'userfield5' OR field = 'userfield6'
					OR field = 'userfield7' OR field = 'userfield8' OR field = 'userfield9' )";
		//echo $query;
		$db->setQuery($query);
		$result = $db->loadObjectList();

		return $result;
	}

	function & getCountrybyId($c_id)
	{
		if (is_numeric($c_id) == false) return false;
		$db = & JFactory :: getDBO();
		$query = "SELECT * FROM #__wrecruit_countries WHERE id = ".$c_id;
		$db->setQuery($query);
		$country = $db->loadObject();
		return $country;
	}

	function getConfigur()
	{
		$db = & JFactory :: getDBO();
                $query = "SELECT * FROM #__wrecruit_config WHERE configname = 'refercode' OR configname = 'versioncode' OR configname = 'versiontype'";
		$db->setQuery($query);
		$confs = $db->loadObjectList();
                foreach($confs AS $conf){
                    if($conf->configname == 'refercode') $rcode = $conf->configvalue;
                    if($conf->configname == 'versioncode') $vcode = $conf->configvalue;
                    if($conf->configname == 'versiontype') $vtype = $conf->configvalue;
                }
		if ($rcode == '0'){
			$row = & $this->getTable('config');
			$reser_med = date('misyHd');
			$reser_med = md5($reser_med);
			$reser_med = md5($reser_med);
			$reser_med	=	substr($reser_med,0,10);
			$string = md5(time());
			$reser_start	=	substr($string,0,5);
			$reser_end =		substr($string,4,3);
			$value =  $reser_start.$reser_med.$reser_end;

			$config['configname'] = 'refercode';
			$config['configvalue'] = $value;
			if (!$row->bind($config)){	$this->setError($this->_db->getErrorMsg());	return false;	}
			if (!$row->store())	{	$this->setError($this->_db->getErrorMsg());	return false;	}
		}else $value = 	$rcode;

                $result[0] = $value;
                $result[1] = $vcode;
                $result[2] = $vtype;
		
                return $result;

	}

	function storeActivate()
	{
		$db = & JFactory :: getDBO();
		$query = "SELECT * FROM #__wrecruit_config WHERE configname = 'refercode'";
		$db->setQuery($query);
		$conf = $db->loadObject();
		if ($conf->configvalue != '0'){
			$row = & $this->getTable('config');
			$data = JRequest :: get('post');
			$str2 = $data['activationkey'];
			$reser_start = substr($conf->configvalue,2,3);
			$reser_med = substr($conf->configvalue,7,3);
			$reser_end = substr($conf->configvalue,12,3);
			$fstr = $reser_start.$reser_med.$reser_end;
			$reser_start = substr($str2,2,3);
			$reser_med = substr($str2,7,3);
			$reser_end = substr($str2,12,3);
			$sstr = $reser_start.$reser_med.$reser_end;
			if (strcmp($fstr,$sstr) == 0){
				$config['configname'] = 'actk';
				$config['configvalue'] = $data['activationkey'];
				if (!$row->bind($config)){	$this->setError($this->_db->getErrorMsg());	return false;	}
				if (!$row->store())	{	$this->setError($this->_db->getErrorMsg());	return false;	}
				$config['configname'] = 'offline'; $config['configvalue'] = 0;
				if (!$row->bind($config)){	$this->setError($this->_db->getErrorMsg());	return false;	}
				if (!$row->store())	{	$this->setError($this->_db->getErrorMsg());	return false;	}
				$config['configname'] = 'fr_cr_txsh';
				$config['configvalue'] = '0';
				if (!$row->bind($config)){	$this->setError($this->_db->getErrorMsg());	return false;	}
				if (!$row->store())	{	$this->setError($this->_db->getErrorMsg());	return false;	}
			}else return 3;
		}else return 4;

		return true;

	}

// Get By Id End

// Get All Start

	function & getAllCategories($limitstart, $limit)
	{
		$db = & JFactory :: getDBO();
		$result = array();
		$query = "SELECT COUNT(id) FROM #__wrecruit_categories";
		$db->setQuery($query);
		$total = $db->loadResult();

		if ( $total <= $limitstart ) $limitstart = 0;
		$query = "SELECT * FROM #__wrecruit_categories ORDER BY cat_title ASC";
		//echo $query;
		$db->setQuery($query,$limitstart, $limit);
		$this->_application = $db->loadObjectList();

		$result[0] = $this->_application;
		$result[1] = $total;
		//return $this->_application;
		return $result;
	}

	function & getSubCategories($categoryid, $limitstart, $limit)
	{
		 if (is_numeric($categoryid) == false) return false;
		$db = & JFactory :: getDBO();
		$result = array();
		$query = "SELECT COUNT(id) FROM #__wrecruit_subcategories WHERE categoryid = ".$categoryid;
		$db->setQuery($query);
		$total = $db->loadResult();

		if ( $total <= $limitstart ) $limitstart = 0;
		$query = "SELECT subcategory.*,category.cat_title FROM #__wrecruit_subcategories AS subcategory
                            JOIN #__wrecruit_categories AS category ON category.id = subcategory.categoryid 
                            WHERE subcategory.categoryid = ".$categoryid." ORDER BY id ASC";
		//echo $query;
		$db->setQuery($query,$limitstart, $limit);
		$subcategories = $db->loadObjectList();

		$result[0] = $subcategories;
		$result[1] = $total;
		return $result;
	}

    function & getAllJobTypes($limitstart, $limit)
	{
		$db = & JFactory :: getDBO();
		$result = array();
		$query = "SELECT COUNT(id) FROM #__wrecruit_jobtypes";
		$db->setQuery($query);
		$total = $db->loadResult();

		if ( $total <= $limitstart ) $limitstart = 0;
		$query = "SELECT * FROM #__wrecruit_jobtypes ORDER BY id ASC";
		//echo $query;
		$db->setQuery($query,$limitstart, $limit);

		$result[0] = $db->loadObjectList();
		$result[1] = $total;
		//return $this->_application;
		return $result;
	}

    function & getAllAges($limitstart, $limit)
	{
		$db = & JFactory :: getDBO();
		$result = array();
		$query = "SELECT COUNT(id) FROM #__wrecruit_ages";
		$db->setQuery($query);
		$total = $db->loadResult();

		if ( $total <= $limitstart ) $limitstart = 0;
		$query = "SELECT * FROM #__wrecruit_ages ORDER BY id ASC";
		//echo $query;
		$db->setQuery($query,$limitstart, $limit);

		$result[0] = $db->loadObjectList();
		$result[1] = $total;
		//return $this->_application;
		return $result;
	}
    function & getAllCareerLevels($limitstart, $limit)
	{
		$db = & JFactory :: getDBO();
		$result = array();
		$query = "SELECT COUNT(id) FROM #__wrecruit_careerlevels";
		$db->setQuery($query);
		$total = $db->loadResult();

		if ( $total <= $limitstart ) $limitstart = 0;
		$query = "SELECT * FROM #__wrecruit_careerlevels ORDER BY id ASC";
		//echo $query;
		$db->setQuery($query,$limitstart, $limit);

		$result[0] = $db->loadObjectList();
		$result[1] = $total;
		//return $this->_application;
		return $result;
	}
    function & getAllExperience($limitstart, $limit)
	{
		$db = & JFactory :: getDBO();
		$result = array();
		$query = "SELECT COUNT(id) FROM #__wrecruit_experiences";
		$db->setQuery($query);
		$total = $db->loadResult();

		if ( $total <= $limitstart ) $limitstart = 0;
		$query = "SELECT * FROM #__wrecruit_experiences ORDER BY id ASC";
		//echo $query;
		$db->setQuery($query,$limitstart, $limit);

		$result[0] = $db->loadObjectList();
		$result[1] = $total;
		//return $this->_application;
		return $result;
	}
    function & getAllSalaryRangeType($limitstart, $limit)
	{
		$db = & JFactory :: getDBO();
		$result = array();
		$query = "SELECT COUNT(id) FROM #__wrecruit_salaryrangetypes";
		$db->setQuery($query);
		$total = $db->loadResult();

		if ( $total <= $limitstart ) $limitstart = 0;
		$query = "SELECT * FROM #__wrecruit_salaryrangetypes ORDER BY id ASC";
		//echo $query;
		$db->setQuery($query,$limitstart, $limit);

		$result[0] = $db->loadObjectList();
		$result[1] = $total;
		//return $this->_application;
		return $result;
	}

	function & getAllJobStatus($limitstart, $limit)
	{
		$db = & JFactory :: getDBO();
		$result = array();
		$query = "SELECT COUNT(id) FROM #__wrecruit_jobstatus";
		$db->setQuery($query);
		$total = $db->loadResult();

		if ( $total <= $limitstart ) $limitstart = 0;
		$query = "SELECT * FROM #__wrecruit_jobstatus ORDER BY id ASC";
		//echo $query;
		$db->setQuery($query,$limitstart, $limit);

		$result[0] = $db->loadObjectList();
		$result[1] = $total;
		//return $this->_application;
		return $result;
	}

	function & getAllShifts($limitstart, $limit)
	{
		$db = & JFactory :: getDBO();
		$result = array();
		$query = "SELECT COUNT(id) FROM #__wrecruit_shifts";
		$db->setQuery($query);
		$total = $db->loadResult();

		if ( $total <= $limitstart ) $limitstart = 0;
		$query = "SELECT * FROM #__wrecruit_shifts ORDER BY id ASC";
		//echo $query;
		$db->setQuery($query,$limitstart, $limit);

		$result[0] = $db->loadObjectList();
		$result[1] = $total;
		//return $this->_application;
		return $result;
	}

	function & getAllHighestEducations($limitstart, $limit)
	{
		$db = & JFactory :: getDBO();
		$result = array();
		$query = "SELECT COUNT(id) FROM #__wrecruit_heighesteducation";
		$db->setQuery($query);
		$total = $db->loadResult();

		if ( $total <= $limitstart ) $limitstart = 0;
		$query = "SELECT * FROM #__wrecruit_heighesteducation ORDER BY id ASC";
		//echo $query;
		$db->setQuery($query,$limitstart, $limit);

		$result[0] = $db->loadObjectList();
		$result[1] = $total;
		//return $this->_application;
		return $result;
	}
	function getAllCurrencies( $limitstart, $limit )
	{
		$db =& JFactory::getDBO();
		$query = "SELECT count(id) FROM ".$db->nameQuote('#__wrecruit_currencies');
		$db->setQuery( $query );
		$total = $db->loadResult();

		if ( $total <= $limitstart ) $limitstart = 0;

		$query = "SELECT * FROM ".$db->nameQuote('#__wrecruit_currencies')." ORDER BY title ASC ";
		$db->setQuery( $query ,$limitstart,$limit );
		$currencyresults = $db->loadObjectList();

		$result[0] = $currencyresults;
		$result[1] = $total;

		return $result;
	}

/* zain */
	function & getAllFolders($uid,$limitstart, $limit)
	{
		$db = & JFactory :: getDBO();
		if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		$result = array();
		$query = "SELECT COUNT(id) FROM #__wrecruit_folders";
		$db->setQuery($query);
		$total = $db->loadResult();

		if ( $total <= $limitstart ) $limitstart = 0;
                $query = "SELECT folder.*,company.name as companyname
                                , ( SELECT count(id) FROM ".$db->nameQuote('#__wrecruit_folderresumes')." WHERE folder.id = folderid) AS nor
			FROM ".$db->nameQuote('#__wrecruit_folders')." AS folder
			JOIN ".$db->nameQuote('#__wrecruit_companies')." AS company ON company.uid = folder.uid
			WHERE folder.status <> 0";
		$db->setQuery($query, $limitstart, $limit);
                //echo'<br>'.$query;
		$result[0] = $db->loadObjectList();
		$result[1] = $total;
		//return $this->_application;
		return $result;
	}

	function & getAllUnapprovedFolders( $limitstart, $limit)
	{
		$db = & JFactory :: getDBO();
		$result = array();
		$query = "SELECT COUNT(id) FROM #__wrecruit_folders AS folder WHERE folder.status = 0";

		$db->setQuery($query);
		$total = $db->loadResult();
                if ( $total <= $limitstart ) $limitstart = 0;

		$query = "SELECT folder.*,company.name as companyname
				FROM ".$db->nameQuote('#__wrecruit_folders')." AS folder
				JOIN ".$db->nameQuote('#__wrecruit_companies')." AS company ON company.uid = folder.uid
				WHERE folder.status = 0";

		$query .= " ORDER BY folder.created DESC";

		//echo $query;
		$db->setQuery($query,$limitstart, $limit);
		$this->_application = $db->loadObjectList();

		$result[0] = $this->_application;
		$result[1] = $total;
		//return $this->_application;
		return $result;
	}
	function & getAllCompanies($searchcompany, $searchjobcategory, $searchcountry, $limitstart, $limit)
	{
		if ($searchjobcategory) if (is_numeric($searchjobcategory) == false) return false;
		$db = & JFactory :: getDBO();
		$result = array();
		$query = "SELECT COUNT(id) FROM #__wrecruit_companies AS company WHERE company.status <> 0";
		if ($searchcompany) $query .= " AND LOWER(company.name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchcompany, true ).'%', false );
		if ($searchjobcategory) $query .= " AND company.category = ".$searchjobcategory;
		if ($searchcountry) $query .= " AND company.country = ".$db->Quote($searchcountry);
		
		$db->setQuery($query);
		$total = $db->loadResult();
                if ( $total <= $limitstart ) $limitstart = 0;

		$query = "SELECT company.*, cat.cat_title , country.name AS countryname
				FROM #__wrecruit_companies AS company  
				JOIN #__wrecruit_categories AS cat ON company.category = cat.id
				JOIN #__wrecruit_countries AS country ON company.country = country.code
				WHERE company.status <> 0";
		if ($searchcompany) $query .= " AND LOWER(company.name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchcompany, true ).'%', false );
		if ($searchjobcategory) $query .= " AND company.category = ".$searchjobcategory;
		if ($searchcountry) $query .= " AND company.country = ".$db->Quote($searchcountry);
		
		$query .= " ORDER BY company.created DESC";

		//echo $query;
		$db->setQuery($query,$limitstart, $limit);
		$this->_application = $db->loadObjectList();

			$lists = array();
			
								
			$job_categories = $this->getCategories(JText::_('JS_SELECT_JOB_CATEGORY'),'');
			$countries = $this->getCountries(JText::_('JS_SELECT_COUNTRY'));
			if ($searchcompany) $lists['searchcompany'] = $searchcompany;
			if($searchjobcategory) 
				$lists['jobcategory'] = JHTML::_('select.genericList', $job_categories, 'searchjobcategory', 'class="inputbox" '.'onChange="this.form.submit();"', 'value', 'text', $searchjobcategory );
			else
				$lists['jobcategory'] = JHTML::_('select.genericList', $job_categories, 'searchjobcategory', 'class="inputbox" '.'onChange="this.form.submit();"', 'value', 'text', '' );
			if ($searchcountry)
				$lists['country'] = JHTML::_('select.genericList', $countries, 'searchcountry', 'class="inputbox" '.'onChange="document.adminForm.submit();"', 'value', 'text', $searchcountry);
			else	
				$lists['country'] = JHTML::_('select.genericList', $countries, 'searchcountry', 'class="inputbox" '.'onChange="document.adminForm.submit();"', 'value', 'text', '');
		
		
		$result[0] = $this->_application;
		$result[1] = $total;
		$result[2] = $lists;
		//return $this->_application;
		return $result;
	}

	function & getAllUnapprovedCompanies($searchcompany, $searchjobcategory, $searchcountry, $limitstart, $limit)
	{
		if ($searchjobcategory) if (is_numeric($searchjobcategory) == false) return false;
		$db = & JFactory :: getDBO();
		$result = array();
		$query = "SELECT COUNT(id) FROM #__wrecruit_companies AS company WHERE company.status = 0";
		if ($searchcompany) $query .= " AND LOWER(company.name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchcompany, true ).'%', false );
		if ($searchjobcategory) $query .= " AND company.category = ".$searchjobcategory;
		if ($searchcountry) $query .= " AND company.country = ".$db->Quote($searchcountry);
		
		$db->setQuery($query);
		$total = $db->loadResult();
                if ( $total <= $limitstart ) $limitstart = 0;

		$query = "SELECT company.*, cat.cat_title , country.name AS countryname
				FROM #__wrecruit_companies AS company  
				JOIN #__wrecruit_categories AS cat ON company.category = cat.id
				JOIN #__wrecruit_countries AS country ON company.country = country.code
				WHERE company.status = 0";
		if ($searchcompany) $query .= " AND LOWER(company.name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchcompany, true ).'%', false );
		if ($searchjobcategory) $query .= " AND company.category = ".$searchjobcategory;
		if ($searchcountry) $query .= " AND company.country = ".$db->Quote($searchcountry);
		
		$query .= " ORDER BY company.created DESC";

		//echo $query;
		$db->setQuery($query,$limitstart, $limit);
		$this->_application = $db->loadObjectList();

			$lists = array();
			
								
			$job_categories = $this->getCategories(JText::_('JS_SELECT_JOB_CATEGORY'),'');
			$countries = $this->getCountries(JText::_('JS_SELECT_COUNTRY'));
			if ($searchcompany) $lists['searchcompany'] = $searchcompany;
			if($searchjobcategory) 
				$lists['jobcategory'] = JHTML::_('select.genericList', $job_categories, 'searchjobcategory', 'class="inputbox" '.'onChange="this.form.submit();"', 'value', 'text', $searchjobcategory );
			else
				$lists['jobcategory'] = JHTML::_('select.genericList', $job_categories, 'searchjobcategory', 'class="inputbox" '.'onChange="this.form.submit();"', 'value', 'text', '' );
			if ($searchcountry)
				$lists['country'] = JHTML::_('select.genericList', $countries, 'searchcountry', 'class="inputbox" '.'onChange="document.adminForm.submit();"', 'value', 'text', $searchcountry);
			else	
				$lists['country'] = JHTML::_('select.genericList', $countries, 'searchcountry', 'class="inputbox" '.'onChange="document.adminForm.submit();"', 'value', 'text', '');
		
		
		$result[0] = $this->_application;
		$result[1] = $total;
		$result[2] = $lists;
		//return $this->_application;
		return $result;
	}

	function & getAllJobs($searchtitle, $searchcompany, $searchjobcategory, $searchjobtype,  $limitstart, $limit)
	{
		if ($searchjobcategory) if (is_numeric($searchjobcategory) == false) return false;
		if($searchjobtype) if (is_numeric($searchjobtype) == false) return false;

		$db = & JFactory :: getDBO();
		$result = array();
		$query = "SELECT COUNT(job.id) FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job
					LEFT JOIN ".$db->nameQuote('#__wrecruit_companies')." AS company ON job.companyid = company.id 
					WHERE job.status <> 0";
		if ($searchtitle) $query .= " AND LOWER(job.title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchtitle, true ).'%', false );
		if ($searchcompany) $query .= " AND LOWER(company.name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchcompany, true ).'%', false );
		if ($searchjobcategory) $query .= " AND job.jobcategory = ".$searchjobcategory;
		if ($searchjobtype) $query .= " AND job.jobtype = ".$searchjobtype;
		
		
		$db->setQuery($query);
		$total = $db->loadResult();
                if ( $total <= $limitstart ) $limitstart = 0;

		$query = "SELECT job.*, cat.cat_title, jobtype.title AS jobtypetitle, company.name AS companyname  
				FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job 
				JOIN ".$db->nameQuote('#__wrecruit_categories')." AS cat ON job.jobcategory = cat.id
				JOIN ".$db->nameQuote('#__wrecruit_jobtypes')." AS jobtype ON job.jobtype = jobtype.id 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_companies')." AS company ON job.companyid = company.id 
				WHERE job.status <> 0";
		if ($searchtitle) $query .= " AND LOWER(job.title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchtitle, true ).'%', false );
		if ($searchcompany) $query .= " AND LOWER(company.name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchcompany, true ).'%', false );
		if ($searchjobcategory) $query .= " AND job.jobcategory = ".$searchjobcategory;
		if ($searchjobtype) $query .= " AND job.jobtype = ".$searchjobtype;
		
		$query .= " ORDER BY job.created DESC";

		//echo $query;
		$db->setQuery($query,$limitstart, $limit);
		$this->_application = $db->loadObjectList();

			$lists = array();
			
			$job_type = $this->getJobType(JText::_('JS_SELECT_JOB_TYPE'));
								
			$job_categories = $this->getCategories(JText::_('JS_SELECT_JOB_CATEGORY'),'');
			if ($searchtitle) $lists['searchtitle'] = $searchtitle;
			if ($searchcompany) $lists['searchcompany'] = $searchcompany;
			if($searchjobcategory) 
				$lists['jobcategory'] = JHTML::_('select.genericList', $job_categories, 'searchjobcategory', 'class="inputbox" '.'onChange="this.form.submit();"'.'style="width:115px"', 'value', 'text', $searchjobcategory );
			else
				$lists['jobcategory'] = JHTML::_('select.genericList', $job_categories, 'searchjobcategory', 'class="inputbox" '.'onChange="this.form.submit();"'.'style="width:115px"', 'value', 'text', '' );
			if ($searchjobtype)
				$lists['jobtype'] = JHTML::_('select.genericList', $job_type, 'searchjobtype', 'class="inputbox" '.'onChange="document.adminForm.submit();"', 'value', 'text', $searchjobtype);
			else	
				$lists['jobtype'] = JHTML::_('select.genericList', $job_type, 'searchjobtype', 'class="inputbox" '.'onChange="document.adminForm.submit();"', 'value', 'text', '');
			
		
		$result[0] = $this->_application;
		$result[1] = $total;
		$result[2] = $lists;
		//return $this->_application;
		return $result;
	}
	
	function & getAllCompaniesListing( $limitstart, $limit)
	{
		$db = & JFactory :: getDBO();
		$result = array();
		$query = "SELECT COUNT(id) FROM #__wrecruit_companies AS company WHERE company.status <> 0";
		$db->setQuery($query);
		$total = $db->loadResult();
                if ( $total <= $limitstart ) $limitstart = 0;

		$query = "SELECT company.*, cat.cat_title , country.name AS countryname
				FROM #__wrecruit_companies AS company  
				JOIN #__wrecruit_categories AS cat ON company.category = cat.id
				JOIN #__wrecruit_countries AS country ON company.country = country.code
				WHERE company.status <> 0";

		
		$query .= " ORDER BY company.created DESC";

		//echo $query;
		$db->setQuery($query,$limitstart, $limit);
		$this->_application = $db->loadObjectList();

			
		$result[0] = $this->_application;
		$result[1] = $total;
		
		return $result;
	}
	
	function & getAllEmpAppsListing( $limitstart, $limit)
	{
		$db = & JFactory :: getDBO();
		$result = array();
		$query = "SELECT COUNT(id) FROM #__wrecruit_resume AS app WHERE app.status <> 0";
		
		$db->setQuery($query);
		$total = $db->loadResult();
                if ( $total <= $limitstart ) $limitstart = 0;

		$query = "SELECT app.id, app.application_title,app.first_name, app.last_name, app.jobtype, 
				app.jobsalaryrange, app.create_date, app.status, cat.cat_title, salary.rangestart, salary.rangeend
				, jobtype.title AS jobtypetitle
				FROM #__wrecruit_resume AS app , #__wrecruit_categories AS cat, #__wrecruit_salaryrange AS salary , #__wrecruit_jobtypes AS jobtype
				WHERE app.job_category = cat.id AND app.jobsalaryrange = salary.id AND app.jobtype = jobtype.id AND app.status <> 0";
		
		$query .= " ORDER BY app.create_date DESC";
		//echo $query;
		$db->setQuery($query,$limitstart, $limit);
		$this->_application = $db->loadObjectList();

		$result[0] = $this->_application;
		$result[1] = $total;
		return $result;
	}
	function & getAllJobListings(  $limitstart, $limit)
	{
		$db = & JFactory :: getDBO();
		$result = array();
		$query = "SELECT COUNT(job.id) FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job
					LEFT JOIN ".$db->nameQuote('#__wrecruit_companies')." AS company ON job.companyid = company.id 
					WHERE job.status <> 0";
		
		
		$db->setQuery($query);
		$total = $db->loadResult();
                if ( $total <= $limitstart ) $limitstart = 0;

		$query = "SELECT job.*, cat.cat_title, jobtype.title AS jobtypetitle, company.name AS companyname  
				FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job 
				JOIN ".$db->nameQuote('#__wrecruit_categories')." AS cat ON job.jobcategory = cat.id
				JOIN ".$db->nameQuote('#__wrecruit_jobtypes')." AS jobtype ON job.jobtype = jobtype.id 
				LEFT JOIN ".$db->nameQuote('#__wrecruit_companies')." AS company ON job.companyid = company.id 
				WHERE job.status <> 0";
		
		
		$query .= " ORDER BY job.created DESC";

		//echo $query;
		$db->setQuery($query,$limitstart, $limit);
		$this->_application = $db->loadObjectList();

			$lists = array();
			
		
		$result[0] = $this->_application;
		$result[1] = $total;
		//return $this->_application;
		return $result;
	}
	function & getAppliedResume($searchtitle, $searchcompany, $searchjobcategory, $searchjobtype, $searchjobstatus, $limitstart, $limit)
	{
		if ($searchjobcategory) if (is_numeric($searchjobcategory) == false) return false;
		if ($searchjobtype) if (is_numeric($searchjobtype) == false) return false;
		if ($searchjobstatus) if (is_numeric($searchjobstatus) == false) return false;
		$db = & JFactory :: getDBO();
		$result = array();
		$query = "SELECT COUNT(job.id) FROM #__wrecruit_jobs AS job
		JOIN ".$db->nameQuote('#__wrecruit_companies')." AS company ON job.companyid = company.id
		WHERE job.status <> 0";
		if ($searchtitle) $query .= " AND LOWER(job.title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchtitle, true ).'%', false );
		if ($searchcompany) $query .= " AND LOWER(company.name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchcompany, true ).'%', false );
		if ($searchjobcategory) $query .= " AND job.jobcategory = ".$searchjobcategory;
		if ($searchjobtype) $query .= " AND job.jobtype = ".$searchjobtype;
		if ($searchjobstatus) $query .= " AND job.jobstatus = ".$searchjobstatus;
		
		$db->setQuery($query);
		$total = $db->loadResult();
                if ( $total <= $limitstart ) $limitstart = 0;

		$query = "SELECT job.*, cat.cat_title, jobtype.title AS jobtypetitle, jobstatus.title AS jobstatustitle, company.name AS companyname
				, ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_jobapply')." WHERE jobid = job.id) AS totalresume
				FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job 
				JOIN ".$db->nameQuote('#__wrecruit_categories')." AS cat ON job.jobcategory = cat.id
				JOIN ".$db->nameQuote('#__wrecruit_jobtypes')." AS jobtype ON job.jobtype = jobtype.id 
				JOIN ".$db->nameQuote('#__wrecruit_jobstatus')." AS jobstatus ON job.jobstatus = jobstatus.id 
				JOIN ".$db->nameQuote('#__wrecruit_companies')." AS company ON job.companyid = company.id
				WHERE job.status <> 0";
		if ($searchtitle) $query .= " AND LOWER(job.title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchtitle, true ).'%', false );
		if ($searchcompany) $query .= " AND LOWER(company.name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchcompany, true ).'%', false );
		if ($searchjobcategory) $query .= " AND job.jobcategory = ".$searchjobcategory;
		if ($searchjobtype) $query .= " AND job.jobtype = ".$searchjobtype;
		if ($searchjobstatus) $query .= " AND job.jobstatus = ".$searchjobstatus;
		
		$query .= " ORDER BY job.created DESC";

		//echo $query;
		$db->setQuery($query,$limitstart, $limit);
		$this->_application = $db->loadObjectList();

			$lists = array();
			
			$job_type = $this->getJobType(JText::_('JS_SELECT_JOB_TYPE'));
			$jobstatus = $this->getJobStatus(JText::_('JS_SELECT_JOB_STATUS'));
								
			$job_categories = $this->getCategories(JText::_('JS_SELECT_JOB_CATEGORY'),'');
			if ($searchtitle) $lists['searchtitle'] = $searchtitle;
			if ($searchcompany) $lists['searchcompany'] = $searchcompany;
			if($searchjobcategory) 
				$lists['jobcategory'] = JHTML::_('select.genericList', $job_categories, 'searchjobcategory', 'class="inputbox" '.'onChange="this.form.submit();"'.'style="width:115px"', 'value', 'text', $searchjobcategory );
			else
				$lists['jobcategory'] = JHTML::_('select.genericList', $job_categories, 'searchjobcategory', 'class="inputbox" '.'onChange="this.form.submit();"'.'style="width:115px"', 'value', 'text', '' );
			if ($searchjobtype)
				$lists['jobtype'] = JHTML::_('select.genericList', $job_type, 'searchjobtype', 'class="inputbox" '.'onChange="document.adminForm.submit();"', 'value', 'text', $searchjobtype);
			else	
				$lists['jobtype'] = JHTML::_('select.genericList', $job_type, 'searchjobtype', 'class="inputbox" '.'onChange="document.adminForm.submit();"', 'value', 'text', '');
			if ($searchjobstatus)
				$lists['jobstatus'] = JHTML::_('select.genericList', $jobstatus, 'searchjobstatus','class="inputbox" '.'onChange="document.adminForm.submit();"'.'style="width:115px"', 'value', 'text', $searchjobstatus);
			else
				$lists['jobstatus'] = JHTML::_('select.genericList', $jobstatus, 'searchjobstatus','class="inputbox" '.'onChange="document.adminForm.submit();"'.'style="width:115px"', 'value', 'text', '');
		
		
		$result[0] = $this->_application;
		$result[1] = $total;
		$result[2] = $lists;
		//return $this->_application;
		return $result;
	}

/* zain */	
        function &getMyFoldersAJAX($uid, $jobid, $resumeid)
	{
		if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		if (is_numeric($jobid) == false) return false;
		if (is_numeric($resumeid) == false) return false;
                $option = 'com_wrecruit';
		$db = &$this->getDBO();
                $canview = 0;
                    $myfolders = $this->getMyFoldersForCombo($uid,'');
                    if($myfolders ) $folders = JHTML::_('select.genericList', $myfolders, 'folderid', 'class="inputbox required" '. '', 'value', 'text', '');
                    else $folders = JText::_('YOU_DO_NOT_HAVE_FOLDERS');

                    $return_value = "<table cellpadding='0' cellspacing='0' border='1' width='100%'>\n";
                            $return_value .= "<tr><td>\n";
                            $return_value .= "<table cellpadding='0' cellspacing='0' border='0' width='100%'>\n";
                            $return_value .= "<tr class='odd'>\n";
                            $return_value .= "<td width='40%' ><b>".JText::_('JS_FOLDER')."</b></td>\n";
                            $return_value .= "<td >".$folders." </td>\n";
                            if($myfolders ){
                                $return_value .= "<td width='20'><input type='button' class='button' onclick='saveaddtofolder(".$jobid.",".$resumeid.")' value='".JText::_('JS_ADD')."'> </td>\n";
                            }
                            $return_value .= "</tr>\n";
                            $return_value .= "</table>\n";
                            $return_value .= "</td></tr>\n";
                            $return_value .= "</table>\n";

		return $return_value;
	}
	function getMyFoldersForCombo( $uid, $title ){
		$db =& JFactory::getDBO();
		if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
                $folders = array();

                $query = "SELECT id, name FROM ".$db->nameQuote('#__wrecruit_folders')." WHERE status = 1 AND uid = ".$uid." ORDER BY name ASC ";

                $db->setQuery( $query );
                $rows = $db->loadObjectList();
                if ($db->getErrorNum()) {
                        echo $db->stderr();
                        return false;
                }

                if($title)
                        $folders[] =  array('value' => JText::_(''),'text' => $title);
                foreach($rows as $row)	{
                        $folders[] =  array('value' => $row->id,'text' => $row->name);
                }
		return $folders;
	}
        function &getResumeCommentsAJAX($id)
	{
		$db = &$this->getDBO();
		if (is_numeric($id) == false) return false;
                $query = "SELECT comments FROM ".$db->nameQuote('#__wrecruit_jobapply')." WHERE id = ".$id;
                $db->setQuery( $query );
                $row = $db->loadObject();
                $option = 'com_wrecruit';
                    $return_value = "<table cellpadding='0' cellspacing='0' border='1' width='100%'>\n";
                            $return_value .= "<tr>\n";
                            $return_value .= "<td width='20%' ><b>".JText::_('JS_COMMENTS')."</b></td>\n";
                            $return_value .= "<td width='65%' align='center'>\n";
                            $return_value .= "<textarea name='comments' rows='3' cols='55'>".$row->comments."</textarea>\n";
                            $return_value .= "</td>\n";
                            $return_value .= "<td align='right' width='15%'><input type='button' class='button' onclick='saveresumecomments(".$id.")' value='".JText::_('JS_SAVE')."'> </td>\n";
                            $return_value .= "</tr>\n";
                            $return_value .= "</table>\n";

		return $return_value;
	}
        function storeFolderResume() //store Folder
	{
		$row = &$this->getTable('folderresume');
		$data = JRequest :: get('post');
                $curdate = date('Y-m-d H:i:s');
		$data['created'] =$curdate ;
		$jobid= $data['jobid'];
                $resumeid = $data['resumeid'];
                $folderid = $data['folderid'];
                if ($this->resumeFolderValidation($jobid,$resumeid,$folderid)) return 3;
                if (!$row->bind($data))	{
                    $this->setError($this->_db->getErrorMsg());
                    return false;
                }
                if (!$row->check())	{
                        $this->setError($this->_db->getErrorMsg());
                        return 2;
                }
                if (!$row->store())	{
                        $this->setError($this->_db->getErrorMsg());
                        return false;
                }
                return true;

	}
        function resumeFolderValidation($jobid,$resumeid,$folderid){
                $db = & JFactory:: getDBO();
		if ((is_numeric($jobid) == false) || ($jobid == 0) || ($jobid == '')) return false;
		if ((is_numeric($resumeid) == false) || ($resumeid == 0) || ($resumeid == '')) return false;
		if ((is_numeric($folderid) == false) || ($folderid == 0) || ($folderid == '')) return false;
                $query = "SELECT COUNT(id) FROM #__wrecruit_folderresumes
		WHERE jobid = ".$jobid." AND resumeid =" .$resumeid." AND folderid = ".$folderid;
		$db->setQuery( $query );
		$result = $db->loadResult();
                if($result > 0) return true;
				else return false;
        }
        function storeResumeRating($uid,$ratingid,$jobid,$resumeid,$newrating) //store Folder
	{
                $row = &$this->getTable('resumerating');
		$db = &$this->getDBO();
		if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		if (is_numeric($jobid) == false) return false;
		if (is_numeric($resumeid) == false) return false;
                $query = "SELECT rating.id
                    FROM ".$db->nameQuote('#__wrecruit_resumerating')." AS rating
                        WHERE rating.jobid = ".$jobid." AND rating.resumeid = ".$resumeid ;
                $db->setQuery( $query );
                $rating = $db->loadObject();



                $row->rating = $newrating;
		if(isset($rating)){
                    $row->id = $rating->id;
                    $row->updated = date('Y-m-d H:i:s');
                }else{
                    $row->created = date('Y-m-d H:i:s');
                    $row->jobid =$jobid;
                    $row->resumeid =$resumeid ;
                    $row->uid =$uid ;
                }

		if (!$row->check())	{
			$this->setError($this->_db->getErrorMsg());
			return 2;
		}
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
                return true;

	}

        function storeResumeComments() //store Folder
	{
		$row = &$this->getTable('jobapply');
		$data = JRequest :: get('post');
		$row->id = $data['id']  ;
		$row->comments =$data['comments'] ;
		if (!$row->check())	{
			$this->setError($this->_db->getErrorMsg());
			return 2;
		}
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}


                //if ($data['id'] == '') $this->sendMailtoAdmin($companyid,$data['uid'],1); //only for new

                return true;

	}

	function storeShortListCandidatee($uid)
	{
		global $resumedata;
		if($uid) if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		$data = JRequest :: get('post');
		if (is_numeric($data['resumeid']) == false) return false;
		if (is_numeric($data['jobid']) == false) return false;
		if (is_numeric($uid) == false) return false;
                if ($this->shortListCandidateValidation($uid,$data['jobid'],$data['resumeid']) == false) return 3;
                $row = &$this->getTable('shortlistcandidate');
                $row->uid = $uid;
                $row->jobid = $data['jobid'];
                $row->cvid = $data['resumeid'];
                $row->status = 0;
                $row->created = date('Y-m-d H:i:s');
		if (!$row->check())	{
			$this->setError($this->_db->getErrorMsg());
			return 2;
		}
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			echo $this->_db->getErrorMsg();
			return false;
		}
		return true;
	}
	function & getJobAppliedResume($jobid, $searchname, $searchjobtype, $limitstart, $limit)
	{
		if (is_numeric($jobid) == false) return false;
		if ($searchjobtype) if (is_numeric($searchjobtype) == false) return false;
		$db = & JFactory :: getDBO();
		$result = array();

		$query = "SELECT COUNT(apply.id) FROM ".$db->nameQuote('#__wrecruit_jobapply')." AS apply 	WHERE  apply.jobid = ".$jobid;

		if ($searchname) {
			$query .= " AND (";
				$query .= " LOWER(app.first_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
				$query .= " OR LOWER(app.last_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
				$query .= " OR LOWER(app.middle_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
			$query .= " )";
		}	
		if ($searchjobtype) $query .= " AND app.jobtype = ".$searchjobtype;
		
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$total = $db->loadResult();
                if ( $total <= $limitstart ) $limitstart = 0;

		$query = "SELECT apply.comments,apply.id AS jobapplyid ,job.id,job.agefrom,job.ageto, 
		cat.cat_title ,apply.apply_date, apply.resumeview, jobtype.title AS jobtypetitle,
				app.iamavailable, app.id AS appid, app.first_name, app.last_name, app.email_address, 
				app.jobtype,app.gender	,app.total_experience, app.jobsalaryrange,rating.id AS ratingid, rating.rating
				,app.address_city, app.address_county, app.address_state
				,country.name AS countryname,state.name AS statename
				,county.name AS countyname,city.name AS cityname , currency.symbol as symbol
				, salary.rangestart, salary.rangeend,education.title AS educationtitle
				FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job
				JOIN ".$db->nameQuote('#__wrecruit_jobtypes')." AS jobtype ON job.jobtype = jobtype.id
				JOIN ".$db->nameQuote('#__wrecruit_categories')." AS cat ON job.jobcategory = cat.id
				JOIN ".$db->nameQuote('#__wrecruit_jobapply')." AS apply  ON apply.jobid = job.id
				JOIN ".$db->nameQuote('#__wrecruit_resume')." AS app ON apply.cvid = app.id
				LEFT JOIN ".$db->nameQuote('#__wrecruit_shortlistcandidates')." AS candidate ON job.id=candidate.jobid
				LEFT JOIN  ".$db->nameQuote('#__wrecruit_resumerating')." AS rating ON (app.id=rating.resumeid AND apply.jobid=rating.jobid)
				LEFT JOIN ".$db->nameQuote('#__wrecruit_heighesteducation')." AS  education  ON app.heighestfinisheducation=education.id
				LEFT JOIN  ".$db->nameQuote('#__wrecruit_salaryrange')." AS salary	ON	app.jobsalaryrange=salary.id
				LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS country ON app.address_country  = country.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS state ON app.address_state = state.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS county ON app.address_county  = county.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS city ON app.address_city = city.code
				LEFT JOIN ".$db->nameQuote('#__wrecruit_currencies')." AS currency ON currency.id = job.currencyid

		WHERE job.id = ".$jobid;
		//echo '<br>'.$query;
		if ($searchname) {
			$query .= " AND (";
				$query .= " LOWER(app.first_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
				$query .= " OR LOWER(app.last_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
				$query .= " OR LOWER(app.middle_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
			$query .= " )";
		}	
		if ($searchjobtype) $query .= " AND app.jobtype = ".$searchjobtype;
		
		$query .= " ORDER BY apply.apply_date DESC";

		//echo $query;
		$db->setQuery($query,$limitstart, $limit);
		$this->_application = $db->loadObjectList();

			$lists = array();
			
			$job_type = $this->getJobType(JText::_('JS_SELECT_JOB_TYPE'));
								
			if ($searchname) $lists['searchname'] = $searchname;
			if ($searchjobtype)
				$lists['jobtype'] = JHTML::_('select.genericList', $job_type, 'searchjobtype', 'class="inputbox" '.'onChange="document.adminForm.submit();"', 'value', 'text', $searchjobtype);
			else	
				$lists['jobtype'] = JHTML::_('select.genericList', $job_type, 'searchjobtype', 'class="inputbox" '.'onChange="document.adminForm.submit();"', 'value', 'text', '');
		
		
		$result[0] = $this->_application;
		$result[1] = $total;
		$result[2] = $lists;
		//return $this->_application;
		return $result;
	}
	function & getFolderResume($folderid, $searchname, $searchjobtype, $limitstart, $limit)
	{
		if (is_numeric($folderid) == false) return false;
		if ($searchjobtype) if (is_numeric($searchjobtype) == false) return false;
		$db = & JFactory :: getDBO();
		$result = array();

		$query = "SELECT COUNT(apply.id) FROM ".$db->nameQuote('#__wrecruit_jobapply')." AS apply 	WHERE  apply.jobid = ".$jobid;

		if ($searchname) {
			$query .= " AND (";
				$query .= " LOWER(app.first_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
				$query .= " OR LOWER(app.last_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
				$query .= " OR LOWER(app.middle_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
			$query .= " )";
		}
		if ($searchjobtype) $query .= " AND app.jobtype = ".$searchjobtype;

		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$total = $db->loadResult();
                if ( $total <= $limitstart ) $limitstart = 0;

		$query = "SELECT  apply.comments,apply.id, cat.cat_title ,apply.apply_date, jobtype.title AS jobtypetitle
                        , app.id AS appid, app.first_name, app.last_name, app.email_address, app.jobtype,app.gender
                        ,app.total_experience, app.jobsalaryrange, salary.rangestart, salary.rangeend, rating.rating,rating.id AS ratingid
                        ,app.address_city, app.address_county, app.address_state
                        ,country.name AS countryname,state.name AS statename
                        ,county.name AS countyname,city.name AS cityname
                        FROM ".$db->nameQuote('#__wrecruit_resume')." AS app
                        JOIN ".$db->nameQuote('#__wrecruit_jobtypes')." AS jobtype ON app.jobtype = jobtype.id
                        JOIN ".$db->nameQuote('#__wrecruit_categories')." AS cat ON app.job_category = cat.id
                        JOIN ".$db->nameQuote('#__wrecruit_jobapply')." AS apply  ON apply.cvid = app.id
						LEFT JOIN  ".$db->nameQuote('#__wrecruit_resumerating')." AS rating ON (app.id=rating.resumeid AND apply.jobid=rating.jobid)
                        LEFT JOIN  ".$db->nameQuote('#__wrecruit_salaryrange')." AS salary ON app.jobsalaryrange=salary.id
                        LEFT JOIN  ".$db->nameQuote('#__wrecruit_folderresumes')." AS fres ON (app.id=fres.resumeid AND apply.jobid=fres.jobid)
                        LEFT JOIN ".$db->nameQuote('#__wrecruit_countries')." AS country ON app.address_country  = country.code
                        LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS state ON app.address_state = state.code
                        LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS county ON app.address_county  = county.code
                        LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS city ON app.address_city = city.code
		WHERE fres.folderid = ".$folderid;
		//echo '<br>'.$query;
		if ($searchname) {
			$query .= " AND (";
				$query .= " LOWER(app.first_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
				$query .= " OR LOWER(app.last_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
				$query .= " OR LOWER(app.middle_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
			$query .= " )";
		}
		if ($searchjobtype) $query .= " AND app.jobtype = ".$searchjobtype;

		$query .= " ORDER BY apply.apply_date DESC";

		//echo $query;
		$db->setQuery($query,$limitstart, $limit);
		$this->_application = $db->loadObjectList();

			$lists = array();

			$job_type = $this->getJobType(JText::_('JS_SELECT_JOB_TYPE'));

			if ($searchname) $lists['searchname'] = $searchname;
			if ($searchjobtype)
				$lists['jobtype'] = JHTML::_('select.genericList', $job_type, 'searchjobtype', 'class="inputbox" '.'onChange="document.adminForm.submit();"', 'value', 'text', $searchjobtype);
			else
				$lists['jobtype'] = JHTML::_('select.genericList', $job_type, 'searchjobtype', 'class="inputbox" '.'onChange="document.adminForm.submit();"', 'value', 'text', '');


		$result[0] = $this->_application;
		$result[1] = $total;
		$result[2] = $lists;
		//return $this->_application;
		return $result;
	}
	function & getShortListCandidates($jobid, $searchname, $searchjobtype, $limitstart, $limit)
	{
		if (is_numeric($jobid) == false) return false;
		if ($searchjobtype) if (is_numeric($searchjobtype) == false) return false;
		$db = & JFactory :: getDBO();
		$result = array();

		$query = "SELECT COUNT(shortlist.id) FROM ".$db->nameQuote('#__wrecruit_shortlistcandidates')." AS shortlist WHERE  shortlist.jobid = ".$jobid;

		if ($searchname) {
			$query .= " AND (";
				$query .= " LOWER(app.first_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
				$query .= " OR LOWER(app.last_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
				$query .= " OR LOWER(app.middle_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
			$query .= " )";
		}
		if ($searchjobtype) $query .= " AND app.jobtype = ".$searchjobtype;

		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$total = $db->loadResult();
                if ( $total <= $limitstart ) $limitstart = 0;

		$query = "SELECT cat.cat_title ,apply.apply_date, jobtype.title AS jobtypetitle
				, app.id AS appid, app.first_name, app.last_name, app.email_address, app.jobtype
				, app.jobsalaryrange, salary.rangestart, salary.rangeend
				FROM ".$db->nameQuote('#__wrecruit_resume')." AS app
				JOIN ".$db->nameQuote('#__wrecruit_jobtypes')." AS jobtype ON app.jobtype = jobtype.id
				JOIN ".$db->nameQuote('#__wrecruit_categories')." AS cat ON app.job_category = cat.id
				JOIN ".$db->nameQuote('#__wrecruit_shortlistcandidates')." AS shortlist ON shortlist.cvid = app.id
				LEFT OUTER JOIN  ".$db->nameQuote('#__wrecruit_salaryrange')." AS salary	ON	app.jobsalaryrange=salary.id
		WHERE shortlist.jobid = ".$jobid;

		if ($searchname) {
			$query .= " AND (";
				$query .= " LOWER(app.first_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
				$query .= " OR LOWER(app.last_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
				$query .= " OR LOWER(app.middle_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
			$query .= " )";
		}
		if ($searchjobtype) $query .= " AND app.jobtype = ".$searchjobtype;

		$query .= " ORDER BY apply.apply_date DESC";

		//echo $query;
		$db->setQuery($query,$limitstart, $limit);
		$this->_application = $db->loadObjectList();

			$lists = array();

			$job_type = $this->getJobType(JText::_('JS_SELECT_JOB_TYPE'));

			if ($searchname) $lists['searchname'] = $searchname;
			if ($searchjobtype)
				$lists['jobtype'] = JHTML::_('select.genericList', $job_type, 'searchjobtype', 'class="inputbox" '.'onChange="document.adminForm.submit();"', 'value', 'text', $searchjobtype);
			else
				$lists['jobtype'] = JHTML::_('select.genericList', $job_type, 'searchjobtype', 'class="inputbox" '.'onChange="document.adminForm.submit();"', 'value', 'text', '');


		$result[0] = $this->_application;
		$result[1] = $total;

		$result[2] = $lists;
		//return $this->_application;
		return $result;
	}
	function & getCompanyDepartments($companyid,$searchcompany,$searchdepartment,$limitstart, $limit)
	{
		if (is_numeric($companyid) == false) return false;
		$db = & JFactory :: getDBO();
		$result = array();
		$lists = array();

		$query = "SELECT COUNT(department.id)
			FROM ".$db->nameQuote('#__wrecruit_departments')." AS department
			JOIN ".$db->nameQuote('#__wrecruit_companies')." AS company ON company.id = department.companyid
			WHERE department.companyid =".$companyid;
			if ($searchcompany) $query .= " AND LOWER(company.name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchcompany, true ).'%', false );
		if ($searchdepartment) $query .= " AND LOWER(department.name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchdepartment, true ).'%', false );

		$db->setQuery($query);
		$total = $db->loadResult();
		if ( $total <= $limitstart ) $limitstart = 0;

		$query = "SELECT department.*, company.name as companyname
			FROM ".$db->nameQuote('#__wrecruit_departments')." AS department
			JOIN ".$db->nameQuote('#__wrecruit_companies')." AS company ON company.id = department.companyid
			WHERE department.companyid =".$companyid;
			if ($searchcompany) $query .= " AND LOWER(company.name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchcompany, true ).'%', false );
		if ($searchdepartment) $query .= " AND LOWER(department.name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchdepartment, true ).'%', false );


		//echo $query;
		$db->setQuery($query,$limitstart, $limit);
		$departments = $db->loadObjectList();
		if ($searchcompany) $lists['searchcompany'] = $searchcompany;
		if ($searchdepartment) $lists['searchdepartment'] = $searchdepartment;


		$result[0] = $departments;
		$result[1] = $total;
		 if(isset($lists)) $result[2] = $lists;


		return $result;
	}

	function & getDepartments($searchcompany,$searchdepartment,$limitstart, $limit)
	{
		$db = & JFactory :: getDBO();
		$result = array();


		$query = "SELECT COUNT(department.id)
			FROM ".$db->nameQuote('#__wrecruit_departments')." AS department
			JOIN ".$db->nameQuote('#__wrecruit_companies')." AS company ON company.id = department.companyid
			WHERE department.status <> 0";
			if ($searchcompany) $query .= " AND LOWER(company.name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchcompany, true ).'%', false );
		if ($searchdepartment) $query .= " AND LOWER(department.name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchdepartment, true ).'%', false );

		$db->setQuery($query);
		$total = $db->loadResult();
		if ( $total <= $limitstart ) $limitstart = 0;

		$query = "SELECT department.*, company.name as companyname
			FROM ".$db->nameQuote('#__wrecruit_departments')." AS department
			JOIN ".$db->nameQuote('#__wrecruit_companies')." AS company ON company.id = department.companyid
			WHERE department.status <> 0";
			if ($searchcompany) $query .= " AND LOWER(company.name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchcompany, true ).'%', false );
		if ($searchdepartment) $query .= " AND LOWER(department.name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchdepartment, true ).'%', false );


		//echo $query;
		$db->setQuery($query,$limitstart, $limit);
		$departments = $db->loadObjectList();
                $lists = "";
		if ($searchcompany) $lists['searchcompany'] = $searchcompany;
		if ($searchdepartment) $lists['searchdepartment'] = $searchdepartment;


		$result[0] = $departments;
		$result[1] = $total;
		$result[2] = $lists;
		return $result;
	}

	function & getAllUnapprovedDepartments($searchcompany,$searchdepartment,$limitstart, $limit)
	{
		$db = & JFactory :: getDBO();
		$result = array();
		$query = "SELECT COUNT(department.id)
			FROM ".$db->nameQuote('#__wrecruit_departments')." AS department
			JOIN ".$db->nameQuote('#__wrecruit_companies')." AS company ON company.id = department.companyid
			WHERE department.status = 0";
			if ($searchcompany) $query .= " AND LOWER(company.name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchcompany, true ).'%', false );
		if ($searchdepartment) $query .= " AND LOWER(department.name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchdepartment, true ).'%', false );

		$db->setQuery($query);
		$total = $db->loadResult();

		if ( $total <= $limitstart ) $limitstart = 0;

		$query = "SELECT department.*, company.name as companyname
			FROM ".$db->nameQuote('#__wrecruit_departments')." AS department
			JOIN ".$db->nameQuote('#__wrecruit_companies')." AS company ON company.id = department.companyid
			WHERE department.status = 0";
			if ($searchcompany) $query .= " AND LOWER(company.name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchcompany, true ).'%', false );
		if ($searchdepartment) $query .= " AND LOWER(department.name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchdepartment, true ).'%', false );


		//echo $query;
		$db->setQuery($query,$limitstart, $limit);
		$departments = $db->loadObjectList();
                $lists = "";

                if ($searchcompany) $lists['searchcompany'] = $searchcompany;
		if ($searchdepartment) $lists['searchdepartment'] = $searchdepartment;


		$result[0] = $departments;
		$result[1] = $total;
		$result[2] = $lists;
		return $result;
	}

	function & getAllEmpApps($searchtitle, $searchname, $searchjobcategory, $searchjobtype, $searchjobsalaryrange, $limitstart, $limit)
	{
		if ($searchjobcategory) if (is_numeric($searchjobcategory) == false) return false;
		if ($searchjobtype) if (is_numeric($searchjobtype) == false) return false;
		if ($searchjobsalaryrange) if (is_numeric($searchjobsalaryrange) == false) return false;
		$db = & JFactory :: getDBO();
		$result = array();
		$query = "SELECT COUNT(id) FROM #__wrecruit_resume AS app WHERE app.status <> 0";
		if ($searchtitle) $query .= " AND LOWER(app.application_title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchtitle, true ).'%', false );
		if ($searchname) {
			$query .= " AND (";
				$query .= " LOWER(app.first_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
				$query .= " OR LOWER(app.last_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
				$query .= " OR LOWER(app.middle_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
			$query .= " )";
		}
		if ($searchjobcategory) $query .= " AND app.job_category = ".$searchjobcategory;
		if ($searchjobtype) $query .= " AND app.jobtype = ".$searchjobtype;
		if ($searchjobsalaryrange) $query .= " AND app.jobsalaryrange = ".$searchjobsalaryrange;
		$db->setQuery($query);
		$total = $db->loadResult();
                if ( $total <= $limitstart ) $limitstart = 0;

		$query = "SELECT app.id, app.application_title,app.first_name, app.last_name, app.jobtype,
				app.jobsalaryrange, app.create_date, app.status, cat.cat_title, salary.rangestart, salary.rangeend , currency.symbol
				, jobtype.title AS jobtypetitle
				FROM #__wrecruit_resume AS app 
					JOIN #__wrecruit_categories AS cat ON app.job_category = cat.id
                    JOIN #__wrecruit_jobtypes AS jobtype	ON app.jobtype = jobtype.id
                    LEFT JOIN #__wrecruit_salaryrange AS salary ON app.jobsalaryrange = salary.id
					LEFT JOIN #__wrecruit_currencies AS currency ON currency.id = app.currencyid
										
				WHERE app.status <> 0  ";
		
		if ($searchtitle) $query .= " AND LOWER(app.application_title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchtitle, true ).'%', false );
		if ($searchname) {
			$query .= " AND (";
				$query .= " LOWER(app.first_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
				$query .= " OR LOWER(app.last_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
				$query .= " OR LOWER(app.middle_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
			$query .= " )";
		}
		if ($searchjobcategory) $query .= " AND app.job_category = ".$searchjobcategory;
		if ($searchjobtype) $query .= " AND app.jobtype = ".$searchjobtype;
		if ($searchjobsalaryrange) $query .= " AND app.jobsalaryrange = ".$searchjobsalaryrange;

		$query .= " ORDER BY app.create_date DESC";
		//echo $query;
		$db->setQuery($query,$limitstart, $limit);
		$this->_application = $db->loadObjectList();

			$lists = array();

			$job_type = array(
				'0' => array('value' => '',	'text' => JText::_('JS_SELECT_JOB_TYPE')),
				'1' => array('value' => JText::_(1),'text' => JText::_('JS_JOBTYPE_FULLTIME')),
				'2' => array('value' => JText::_(2),'text' => JText::_('JS_JOBTYPE_PARTTIME')),
				'3' => array('value' => JText::_(3),'text' => JText::_('JS_JOBTYPE_INTERNSHIP')),);


			$job_categories = $this->getCategories(JText::_('JS_SELECT_JOB_CATEGORY'),'');
			$job_salaryrange = $this->getJobSalaryRange(JText::_('JS_SELECT_SALARY_RANGE'),'');

			if ($searchtitle) $lists['searchtitle'] = $searchtitle;
			if ($searchname) $lists['searchname'] = $searchname;
			if($searchjobcategory)
				$lists['jobcategory'] = JHTML::_('select.genericList', $job_categories, 'searchjobcategory', 'class="inputbox" '.'onChange="this.form.submit();"'.'style="width:115px"', 'value', 'text', $searchjobcategory );
			else
				$lists['jobcategory'] = JHTML::_('select.genericList', $job_categories, 'searchjobcategory', 'class="inputbox" '.'onChange="this.form.submit();"'.'style="width:115px"', 'value', 'text', '' );
			if ($searchjobtype)
				$lists['jobtype'] = JHTML::_('select.genericList', $job_type, 'searchjobtype', 'class="inputbox" '.'onChange="document.adminForm.submit();"', 'value', 'text', $searchjobtype);
			else
				$lists['jobtype'] = JHTML::_('select.genericList', $job_type, 'searchjobtype', 'class="inputbox" '.'onChange="document.adminForm.submit();"', 'value', 'text', '');
			if ($searchjobsalaryrange)
				$lists['jobsalaryrange'] = JHTML::_('select.genericList', $job_salaryrange, 'searchjobsalaryrange','class="inputbox" '.'onChange="document.adminForm.submit();"', 'value', 'text', $searchjobsalaryrange);
			else
				$lists['jobsalaryrange'] = JHTML::_('select.genericList', $job_salaryrange, 'searchjobsalaryrange','class="inputbox" '.'onChange="document.adminForm.submit();"', 'value', 'text', '');

		$result[0] = $this->_application;
		$result[1] = $total;
		$result[2] = $lists;
		return $result;
	}

	function & getAllUnapprovedJobs($searchtitle, $searchcompany, $searchjobcategory, $searchjobtype, $searchjobstatus, $limitstart, $limit)
	{
		if ($searchjobcategory) if (is_numeric($searchjobcategory) == false) return false;
		if ($searchjobtype) if (is_numeric($searchjobtype) == false) return false;
		if ($searchjobstatus) if (is_numeric($searchjobstatus) == false) return false;
		$db = & JFactory :: getDBO();
		$result = array();
		$query = "SELECT COUNT(job.id) FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job
					LEFT JOIN ".$db->nameQuote('#__wrecruit_companies')." AS company ON job.companyid = company.id
					WHERE job.status = 0";
		if ($searchtitle) $query .= " AND LOWER(job.title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchtitle, true ).'%', false );
		if ($searchcompany) $query .= " AND LOWER(company.name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchcompany, true ).'%', false );
		if ($searchjobcategory) $query .= " AND job.jobcategory = ".$searchjobcategory;
		if ($searchjobtype) $query .= " AND job.jobtype = ".$searchjobtype;
		if ($searchjobstatus) $query .= " AND job.jobstatus = ".$searchjobstatus;

		$db->setQuery($query);
		$total = $db->loadResult();
                if ( $total <= $limitstart ) $limitstart = 0;

		$query = "SELECT job.*, cat.cat_title, jobtype.title AS jobtypetitle, jobstatus.title AS jobstatustitle, company.name AS companyname
				FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job
				JOIN ".$db->nameQuote('#__wrecruit_categories')." AS cat ON job.jobcategory = cat.id
				JOIN ".$db->nameQuote('#__wrecruit_jobtypes')." AS jobtype ON job.jobtype = jobtype.id
				JOIN ".$db->nameQuote('#__wrecruit_jobstatus')." AS jobstatus ON job.jobstatus = jobstatus.id
				LEFT JOIN ".$db->nameQuote('#__wrecruit_companies')." AS company ON job.companyid = company.id
				WHERE  job.status = 0 ";
		if ($searchtitle) $query .= " AND LOWER(job.title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchtitle, true ).'%', false );
		if ($searchcompany) $query .= " AND LOWER(company.name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchcompany, true ).'%', false );
		if ($searchjobcategory) $query .= " AND job.jobcategory = ".$searchjobcategory;
		if ($searchjobtype) $query .= " AND job.jobtype = ".$searchjobtype;
		if ($searchjobstatus) $query .= " AND job.jobstatus = ".$searchjobstatus;

		$query .= " ORDER BY job.created DESC";
		//echo $query;
		$db->setQuery($query,$limitstart, $limit);
		$this->_application = $db->loadObjectList();

			$lists = array();

			$job_type = $this->getJobType(JText::_('JS_SELECT_JOB_TYPE'));
			$jobstatus = $this->getJobStatus(JText::_('JS_SELECT_JOB_STATUS'));

			$job_categories = $this->getCategories(JText::_('JS_SELECT_JOB_CATEGORY'),'');
			if ($searchtitle) $lists['searchtitle'] = $searchtitle;
			if ($searchcompany) $lists['searchcompany'] = $searchcompany;
			if($searchjobcategory)
				$lists['jobcategory'] = JHTML::_('select.genericList', $job_categories, 'searchjobcategory', 'class="inputbox" '.'onChange="this.form.submit();"'.'style="width:115px"', 'value', 'text', $searchjobcategory );
			else
				$lists['jobcategory'] = JHTML::_('select.genericList', $job_categories, 'searchjobcategory', 'class="inputbox" '.'onChange="this.form.submit();"'.'style="width:115px"', 'value', 'text', '' );
			if ($searchjobtype)
				$lists['jobtype'] = JHTML::_('select.genericList', $job_type, 'searchjobtype', 'class="inputbox" '.'onChange="document.adminForm.submit();"', 'value', 'text', $searchjobtype);
			else
				$lists['jobtype'] = JHTML::_('select.genericList', $job_type, 'searchjobtype', 'class="inputbox" '.'onChange="document.adminForm.submit();"', 'value', 'text', '');
			if ($searchjobstatus)
				$lists['jobstatus'] = JHTML::_('select.genericList', $jobstatus, 'searchjobstatus','class="inputbox" '.'onChange="document.adminForm.submit();"'.'style="width:115px"', 'value', 'text', $searchjobstatus);
			else
				$lists['jobstatus'] = JHTML::_('select.genericList', $jobstatus, 'searchjobstatus','class="inputbox" '.'onChange="document.adminForm.submit();"'.'style="width:115px"', 'value', 'text', '');

		$result[0] = $this->_application;
		$result[1] = $total;
		$result[2] = $lists;
		return $result;
	}

	function & getAllUnapprovedEmpApps($searchtitle, $searchname, $searchjobcategory, $searchjobtype, $searchjobsalaryrange, $limitstart, $limit)
	{
		if ($searchjobcategory) if (is_numeric($searchjobcategory) == false) return false;
		if ($searchjobtype) if (is_numeric($searchjobtype) == false) return false;
		if ($searchjobsalaryrange) if (is_numeric($searchjobsalaryrange) == false) return false;
		$db = & JFactory :: getDBO();
		$result = array();
		$query = "SELECT COUNT(id) FROM #__wrecruit_resume AS app WHERE status = 0";
		if ($searchtitle) $query .= " AND LOWER(app.application_title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchtitle, true ).'%', false );
		if ($searchname) {
			$query .= " AND (";
				$query .= " LOWER(app.first_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
				$query .= " OR LOWER(app.last_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
				$query .= " OR LOWER(app.middle_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
			$query .= " )";
		}
		if ($searchjobcategory) $query .= " AND app.job_category = ".$searchjobcategory;
		if ($searchjobtype) $query .= " AND app.jobtype = ".$searchjobtype;
		if ($searchjobsalaryrange) $query .= " AND app.jobsalaryrange = ".$searchjobsalaryrange;
		$db->setQuery($query);
		$total = $db->loadResult();
                if ( $total <= $limitstart ) $limitstart = 0;

		$query = "SELECT app.id, app.application_title,app.first_name, app.last_name, app.jobtype,
				app.jobsalaryrange, app.create_date, cat.cat_title , salary.rangestart, salary.rangeend
				, jobtype.title AS jobtypetitle
				FROM #__wrecruit_resume AS app , #__wrecruit_categories AS cat, #__wrecruit_salaryrange AS salary, #__wrecruit_jobtypes AS jobtype
				WHERE app.job_category = cat.id AND app.jobsalaryrange = salary.id AND app.jobtype= jobtype.id AND app.status = 0 ";
		if ($searchtitle) $query .= " AND LOWER(app.application_title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchtitle, true ).'%', false );
		if ($searchname) {
			$query .= " AND (";
				$query .= " LOWER(app.first_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
				$query .= " OR LOWER(app.last_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
				$query .= " OR LOWER(app.middle_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
			$query .= " )";
		}
		if ($searchjobcategory) $query .= " AND app.job_category = ".$searchjobcategory;
		if ($searchjobtype) $query .= " AND app.jobtype = ".$searchjobtype;
		if ($searchjobsalaryrange) $query .= " AND app.jobsalaryrange = ".$searchjobsalaryrange;

		$query .= " ORDER BY app.create_date DESC";
		//echo $query;
		$db->setQuery($query,$limitstart, $limit);
		$this->_application = $db->loadObjectList();

			$lists = array();

			$job_type = array(
				'0' => array('value' => '',	'text' => JText::_('JS_SELECT_JOB_TYPE')),
				'1' => array('value' => JText::_(1),'text' => JText::_('JS_JOBTYPE_FULLTIME')),
				'2' => array('value' => JText::_(2),'text' => JText::_('JS_JOBTYPE_PARTTIME')),
				'3' => array('value' => JText::_(3),'text' => JText::_('JS_JOBTYPE_INTERNSHIP')),);


			$job_categories = $this->getCategories(JText::_('JS_SELECT_JOB_CATEGORY'),'');
			$job_salaryrange = $this->getJobSalaryRange(JText::_('JS_SELECT_SALARY_RANGE'),'');

			if ($searchtitle) $lists['searchtitle'] = $searchtitle;
			if ($searchname) $lists['searchname'] = $searchname;
			if($searchjobcategory)
				$lists['jobcategory'] = JHTML::_('select.genericList', $job_categories, 'searchjobcategory', 'class="inputbox" '.'onChange="this.form.submit();"'.'style="width:115px"', 'value', 'text', $searchjobcategory );
			else
				$lists['jobcategory'] = JHTML::_('select.genericList', $job_categories, 'searchjobcategory', 'class="inputbox" '.'onChange="this.form.submit();"'.'style="width:115px"', 'value', 'text', '' );
			if ($searchjobtype)
				$lists['jobtype'] = JHTML::_('select.genericList', $job_type, 'searchjobtype', 'class="inputbox" '.'onChange="document.adminForm.submit();"', 'value', 'text', $searchjobtype);
			else
				$lists['jobtype'] = JHTML::_('select.genericList', $job_type, 'searchjobtype', 'class="inputbox" '.'onChange="document.adminForm.submit();"', 'value', 'text', '');
			if ($searchjobsalaryrange)
				$lists['jobsalaryrange'] = JHTML::_('select.genericList', $job_salaryrange, 'searchjobsalaryrange','class="inputbox" '.'onChange="document.adminForm.submit();"', 'value', 'text', $searchjobsalaryrange);
			else
				$lists['jobsalaryrange'] = JHTML::_('select.genericList', $job_salaryrange, 'searchjobsalaryrange','class="inputbox" '.'onChange="document.adminForm.submit();"', 'value', 'text', '');

		$result[0] = $this->_application;
		$result[1] = $total;
		$result[2] = $lists;
		//return $this->_application;
		return $result;
	}

	function & getAllMessages($statusoperator, $username, $usertype, $company, $jobtitle, $subject, $limitstart, $limit)
	{
		$db = & JFactory :: getDBO();
		$result = array();
                $userjoin = "";
                $jobjoin = "";
                $wherequery = "";
                $companyjoin = "";
                if ($username) {
                    if($usertype == 1) $userjoin = " JOIN #__users AS user ON user.id = message.employerid"; //employer
                    elseif($usertype == 2) $userjoin = " JOIN #__users AS user ON user.id = message.jobseekerid"; // jobseeker
                }
                
                if ($jobtitle){
                    $jobjoin = " JOIN #__wrecruit_jobs AS job ON job.id = message.jobid";
                    if ($company) $companyjoin = " JOIN #__wrecruit_companies AS company ON company.id = job.companyid";
                }else
                    if ($company) $companyjoin = " JOIN #__wrecruit_jobs AS job ON job.id = message.jobid
                                                    JOIN #__wrecruit_companies AS company ON company.id = job.companyid";

		$query = "SELECT COUNT(message.id) FROM #__wrecruit_messages AS message ".$userjoin.$jobjoin.$companyjoin."
                            WHERE message.status ".$statusoperator." 0";
		if ($username){
			$wherequery .=  ' AND (LOWER(user.name) LIKE '.$db->Quote( '%'.$db->getEscaped( $username, true ).'%', false ).'
                                             OR LOWER(user.username) LIKE '.$db->Quote( '%'.$db->getEscaped( $username, true ).'%', false ).') ';
                }
                if ($jobtitle) $wherequery .=  ' AND LOWER(job.title) LIKE '.$db->Quote( '%'.$db->getEscaped( $jobtitle, true ).'%', false );
                if ($company) $wherequery .=  ' AND LOWER(company.name) LIKE '.$db->Quote( '%'.$db->getEscaped( $company, true ).'%', false );
                if ($subject) $wherequery .=  ' AND LOWER(message.subject) LIKE '.$db->Quote( '%'.$db->getEscaped( $subject, true ).'%', false );

                $query .= $wherequery;
                //echo '<br>'.$query;
		$db->setQuery($query);
		$total = $db->loadResult();
                if ( $total <= $limitstart ) $limitstart = 0;

		$query = "SELECT message.*, job.title as jobtitle, resume.application_title, resume.first_name, resume.middle_name, resume.last_name
                                , empuser.name as employername, jsuser.name as jobseekername, company.name as companyname
				FROM #__wrecruit_messages AS message
                                ".$userjoin."
                                JOIN #__users AS empuser ON empuser.id = message.employerid
                                JOIN #__users AS jsuser ON jsuser.id = message.jobseekerid
				JOIN #__wrecruit_jobs AS job ON job.id = message.jobid
				JOIN #__wrecruit_resume AS resume ON resume.id = message.resumeid
				JOIN #__wrecruit_companies AS company ON company.id = job.companyid
				WHERE message.status ".$statusoperator." 0";
                $query .= $wherequery;
		$query .= " ORDER BY message.created DESC";

		//echo '<br>'. $query;
		$db->setQuery($query,$limitstart, $limit);
		$messages = $db->loadObjectList();

                $lists = array();

                $usertypes = array(
                        '0' => array('value' => 1,'text' => JText::_('JS_EMPLOYER')),
                        '1' => array('value' => 2,'text' => JText::_('JS_JOB_SEEKER')),);
                $conflict = array(
                        '0' => array('value' => 1,'text' => JText::_('JS_YES')),
                        '1' => array('value' => 0,'text' => JText::_('JS_NO')),);

                if ($username) $lists['username'] = $username;
                $lists['usertype'] = JHTML::_('select.genericList', $usertypes, 'message_usertype', 'class="inputbox" '.'', 'value', 'text', $usertype );
                $lists['conflict'] = JHTML::_('select.genericList', $conflict, 'message_conflicted', 'class="inputbox" '.'', 'value', 'text', $conflict );
                if ($jobtitle) $lists['jobtitle'] = $jobtitle;
                if ($company) $lists['company'] = $company;
                if ($subject) $lists['subject'] = $subject;


		$result[0] = $messages;
		$result[1] = $total;
		$result[2] = $lists;
		return $result;
	}

        function & getAllSalaryRange($limitstart, $limit)
	{
		$db = & JFactory :: getDBO();
		$result = array();
		$query = "SELECT COUNT(id) FROM #__wrecruit_salaryrange";
		$db->setQuery($query);
		$total = $db->loadResult();
		if ( $total <= $limitstart ) $limitstart = 0;

		$query = "SELECT * FROM #__wrecruit_salaryrange";
		//echo $query;
		$db->setQuery($query,$limitstart, $limit);
		$this->_application = $db->loadObjectList();

		$result[0] = $this->_application;
		$result[1] = $total;
		//return $this->_application;
		return $result;
	}

	function & getAllRoles($limitstart, $limit)
	{
		$db = & JFactory :: getDBO();
		$result = array();
		$query = "SELECT COUNT(id) FROM #__wrecruit_roles";
		$db->setQuery($query);
		$total = $db->loadResult();
		if ( $total <= $limitstart ) $limitstart = 0;

		$query = "SELECT * FROM #__wrecruit_roles ORDER BY id ASC";
		//echo $query;
		$db->setQuery($query,$limitstart, $limit);
		//$this->_application = $db->loadObjectList();

		$result[0] = $db->loadObjectList();
		$result[1] = $total;
		//return $this->_application;
		return $result;
	}

	function & getAllUsers($searchname,$searchusername,$searchcompany,$searchresume,$searchrole, $limitstart, $limit)
	{
		$db = & JFactory :: getDBO();
		$result = array();

		$query = 'SELECT COUNT(a.id)'
			. ' FROM #__users AS a'
			. ' LEFT JOIN #__wrecruit_userroles AS usr ON usr.uid = a.id '
			. ' LEFT JOIN #__wrecruit_roles AS role ON role.id = usr.role
			 LEFT JOIN #__wrecruit_companies AS company ON company.uid = a.id
			 LEFT JOIN #__wrecruit_resume AS resume ON resume.uid = a.id ';

		$clause=' WHERE ';
		if ($searchname) {
			$query .=  $clause.' LOWER(a.name) LIKE '.$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
			$clause='AND';
		}
		if ($searchusername) {
			$query .=  $clause.' LOWER(a.username) LIKE '.$db->Quote( '%'.$db->getEscaped( $searchusername, true ).'%', false );
			$clause='AND';
		}
		if ($searchcompany) {
			$query .=  $clause.' LOWER(company.name) LIKE '.$db->Quote( '%'.$db->getEscaped( $searchcompany, true ).'%', false );
			$clause='AND';
		}
		if ($searchresume) {
			$query .=  $clause.' ( LOWER(resume.first_name) LIKE '.$db->Quote( '%'.$db->getEscaped( $searchresume, true ).'%', false ).'
                                            OR LOWER(resume.last_name) LIKE '.$db->Quote( '%'.$db->getEscaped( $searchresume, true ).'%', false ).'
                                            OR LOWER(resume.middle_name) LIKE '.$db->Quote( '%'.$db->getEscaped( $searchresume, true ).'%', false ).' )';
			$clause='AND';
                }
		if ($searchrole)
			$query .=  $clause.' LOWER( role.title) LIKE '.$db->Quote( '%'.$db->getEscaped( $searchrole, true ).'%', false );



		$db->setQuery($query);
		$total = $db->loadResult();
		if ( $total <= $limitstart ) $limitstart = 0;
		$version = new JVersion;
		$joomla = $version->getShortVersion();
		$jversion = '1.5';
                if(substr($joomla,0,3) == '1.6') $jversion = '1.6';
                elseif(substr($joomla,0,3) == '1.7') $jversion = '1.7';

                if($jversion == '1.5'){
                    $query = 'SELECT a.*, g.name AS groupname, role.title AS roletitle,
                                     company.name AS companyname, resume.first_name, resume.last_name'
                            . ' FROM #__users AS a'
                            . ' INNER JOIN #__core_acl_aro AS aro ON aro.value = a.id'
                            . ' INNER JOIN #__core_acl_groups_aro_map AS gm ON gm.aro_id = aro.id'
                            . ' INNER JOIN #__core_acl_aro_groups AS g ON g.id = gm.group_id'
                            . ' LEFT JOIN #__wrecruit_userroles AS usr ON usr.uid = a.id '
                            . ' LEFT JOIN #__wrecruit_roles AS role ON role.id = usr.role
                             LEFT JOIN #__wrecruit_companies AS company ON company.uid = a.id
                             LEFT JOIN #__wrecruit_resume AS resume ON resume.uid = a.id ';
                }else{
                    $query = 'SELECT a.*, g.title AS groupname, role.title AS roletitle,
                                     company.name AS companyname, resume.first_name, resume.last_name'
                            . ' FROM #__users AS a'
                            . '	INNER JOIN #__user_usergroup_map AS groupmap ON groupmap.user_id = a.id '
                            . '	INNER JOIN #__usergroups AS g ON g.id = groupmap.group_id '
                            . ' LEFT JOIN #__wrecruit_userroles AS usr ON usr.uid = a.id '
                            . ' LEFT JOIN #__wrecruit_roles AS role ON role.id = usr.role
                             LEFT JOIN #__wrecruit_companies AS company ON company.uid = a.id
                             LEFT JOIN #__wrecruit_resume AS resume ON resume.uid = a.id ';
                }
		$clause=' WHERE ';
		if ($searchname) {
			$query .=  $clause.' LOWER(a.name) LIKE '.$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
			$clause='AND';
		}
		if ($searchusername) {
			$query .=  $clause.' LOWER(a.username) LIKE '.$db->Quote( '%'.$db->getEscaped( $searchusername, true ).'%', false );
			$clause='AND';
		}
		if ($searchcompany) {
			$query .=  $clause.' LOWER(company.name) LIKE '.$db->Quote( '%'.$db->getEscaped( $searchcompany, true ).'%', false );
			$clause='AND';
		}
		if ($searchresume) {
			$query .=  $clause.' ( LOWER(resume.first_name) LIKE '.$db->Quote( '%'.$db->getEscaped( $searchresume, true ).'%', false ).'
                                            OR LOWER(resume.last_name) LIKE '.$db->Quote( '%'.$db->getEscaped( $searchresume, true ).'%', false ).'
                                            OR LOWER(resume.middle_name) LIKE '.$db->Quote( '%'.$db->getEscaped( $searchresume, true ).'%', false ).' )';
			$clause='AND';
                }
		if ($searchrole)
			$query .=  $clause.' LOWER( role.title) LIKE '.$db->Quote( '%'.$db->getEscaped( $searchrole, true ).'%', false );

		$query .= ' GROUP BY a.id';
		//echo $query;
		$db->setQuery($query,$limitstart, $limit);
		$result[0]= $db->loadObjectList();



		$lists = array();
		if ($searchname) $lists['searchname'] = $searchname;
		if ($searchusername) $lists['searchusername'] = $searchusername;
		if ($searchcompany) $lists['searchcompany'] = $searchcompany;
		if ($searchresume) $lists['searchresume'] = $searchresume;
		if ($searchrole) $lists['searchrole'] = $searchrole;
        	//$lists['roles'] = $this->getRoles('');
		$result[1] = $total;
		$result[2] = $lists;
		return $result;
	}


	function & getUserStats($searchname,$searchusername, $limitstart, $limit)
	{
		$db = & JFactory :: getDBO();
		$result = array();

		$query = 'SELECT COUNT(a.id)'
			. ' FROM #__users AS a';

		$clause=' WHERE ';
		if ($searchname) {
			$query .=  $clause.' LOWER(a.name) LIKE '.$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
			$clause='AND';
		}
		if ($searchusername)
			$query .=  $clause.' LOWER(a.username) LIKE '.$db->Quote( '%'.$db->getEscaped( $searchusername, true ).'%', false );



		$db->setQuery($query);
		$total = $db->loadResult();
		if ( $total <= $limitstart ) $limitstart = 0;

		$query = 'SELECT a.*,role.rolefor
                    ,(SELECT name FROM #__wrecruit_companies WHERE uid=a.id limit 1 ) AS companyname
                    ,(SELECT CONCAT(first_name," ",last_name) FROM #__wrecruit_resume WHERE uid=a.id limit 1 ) AS resumename
                    ,(SELECT count(id) FROM #__wrecruit_companies WHERE uid=a.id ) AS companies
                    ,(SELECT count(id) FROM #__wrecruit_jobs WHERE uid=a.id ) AS jobs
                    ,(SELECT count(id) FROM #__wrecruit_resume WHERE uid=a.id ) AS resumes
                    FROM #__users AS a
                    LEFT JOIN #__wrecruit_userroles AS userrole ON userrole.uid=a.id
                    LEFT JOIN #__wrecruit_roles AS role ON role.id=userrole.role';


		$clause=' WHERE ';
		if ($searchname) {
			$query .=  $clause.' LOWER(a.name) LIKE '.$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
			$clause='AND';
		}
		if ($searchusername)
			$query .=  $clause.' LOWER(a.username) LIKE '.$db->Quote( '%'.$db->getEscaped( $searchusername, true ).'%', false );


		$query .= ' GROUP BY a.id';
		//echo $query;
		$db->setQuery($query,$limitstart, $limit);
		$result[0]= $db->loadObjectList();



		$lists = array();
		if ($searchname) $lists['searchname'] = $searchname;


		if ($searchusername) $lists['searchusername'] = $searchusername;



		$result[1] = $total;
		$result[2] = $lists;
		return $result;
	}

	function & getUserStatsCompanies($companyuid,$limitstart, $limit)
	{
		if (is_numeric($companyuid) == false) return false;
		$db = & JFactory :: getDBO();
		$result = array();

		$query = 'SELECT COUNT(company.id)'
		. ' FROM #__wrecruit_companies AS company
		WHERE company.uid = '.$companyuid;

		$db->setQuery($query);
		$total= $db->loadResult();
		if ( $total <= $limitstart ) $limitstart = 0;

		$query = 'SELECT company.*,cat.cat_title,country.name AS countryname'
		. ' FROM #__wrecruit_companies AS company'
		.' JOIN #__wrecruit_categories AS cat ON cat.id=company.category'
		.' JOIN #__wrecruit_countries AS country ON country.code=company.country
		WHERE company.uid = '.$companyuid;

		$query .= ' ORDER BY company.name';
		//echo $query;
		$db->setQuery($query,$limitstart, $limit);
		$result[0]= $db->loadObjectList();
		$result[1] = $total;
		return $result;
	}


	function & getUserStatsJobs($jobuid,$limitstart, $limit)
	{
		if (is_numeric($jobuid) == false) return false;
		$db = & JFactory :: getDBO();
		$result = array();

		$query = 'SELECT COUNT(job.id)'
		. ' FROM #__wrecruit_jobs AS job
		WHERE job.uid = '.$jobuid;

		$db->setQuery($query);
		$total= $db->loadResult();
		if ( $total <= $limitstart ) $limitstart = 0;

		//echo $query;

		$query = 'SELECT job.*,company.name AS companyname,cat.cat_title,jobtype.title AS jobtypetitle'
		. ' FROM #__wrecruit_jobs AS job'
		.' LEFT JOIN #__wrecruit_companies AS company ON company.id=job.companyid'
		.' LEFT JOIN #__wrecruit_categories AS cat ON cat.id=job.jobcategory'
		.' LEFT JOIN #__wrecruit_jobtypes AS jobtype ON jobtype.id=job.jobtype
		   WHERE job.uid = '.$jobuid;
		$query .= ' ORDER BY job.title';
		//echo $query;
		$db->setQuery($query,$limitstart, $limit);
		$result[0]= $db->loadObjectList();
		$result[1] = $total;
		return $result;
	}
	function & getAllCountries($limitstart, $limit)
	{
		$db = & JFactory :: getDBO();
		$result = array();
		$query = "SELECT COUNT(id) FROM #__wrecruit_countries";
		$db->setQuery($query);
		$total = $db->loadResult();
		if ( $total <= $limitstart ) $limitstart = 0;

		$query = "SELECT * FROM #__wrecruit_countries ORDER BY name ASC";
		//echo $query;
		$db->setQuery($query,$limitstart, $limit);

		$result[0] = $db->loadObjectList();
		$result[1] = $total;
		//return $this->_application;
		return $result;
	}

	function & getAllCountryStates($countrycode, $limitstart, $limit)
	{
		$db = & JFactory :: getDBO();
		$result = array();
		$query = "SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_states')." WHERE countrycode = ". $db->Quote($countrycode);
		$db->setQuery($query);
		$total = $db->loadResult();
		if ( $total <= $limitstart ) $limitstart = 0;

		$query = "SELECT * FROM ".$db->nameQuote('#__wrecruit_states')." WHERE countrycode = ". $db->Quote($countrycode) ." ORDER BY name ASC";
		$db->setQuery($query,$limitstart, $limit);

		$result[0] = $db->loadObjectList();
		$result[1] = $total;
		return $result;
	}

	function & getAllStateCounties($statecode, $limitstart, $limit)
	{
		$db = & JFactory :: getDBO();
		$result = array();
		$query = "SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_counties')." WHERE statecode = ". $db->Quote($statecode);
		$db->setQuery($query);
		$total = $db->loadResult();
		if ( $total <= $limitstart ) $limitstart = 0;

		$query = "SELECT * FROM ".$db->nameQuote('#__wrecruit_counties')." WHERE statecode = ". $db->Quote($statecode) ." ORDER BY name ASC";
		$db->setQuery($query,$limitstart, $limit);

		$result[0] = $db->loadObjectList();
		$result[1] = $total;
		return $result;
	}

	function & getAllCountyCities($countycode, $limitstart, $limit)
	{
		$db = & JFactory :: getDBO();
		$result = array();
		$query = "SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_cities')." WHERE countycode = ". $db->Quote($countycode);
		$db->setQuery($query);
		$total = $db->loadResult();
		if ( $total <= $limitstart ) $limitstart = 0;

		$query = "SELECT * FROM ".$db->nameQuote('#__wrecruit_cities')." WHERE countycode = ". $db->Quote($countycode) ." ORDER BY name ASC";
		$db->setQuery($query,$limitstart, $limit);

		$result[0] = $db->loadObjectList();
		$result[1] = $total;
		return $result;
	}

	function & getJobSeekerPackages($limitstart, $limit)
	{
		$db = & JFactory :: getDBO();
		$result = array();
		$query = "SELECT COUNT(id) FROM #__wrecruit_jobseekerpackages";
		$db->setQuery($query);
		$total = $db->loadResult();
		if ( $total <= $limitstart ) $limitstart = 0;

		$query = "SELECT * FROM #__wrecruit_jobseekerpackages ORDER BY id ASC";
		//echo $query;
		$db->setQuery($query,$limitstart, $limit);
		$packages = $db->loadObjectList();

		$result[0] = $packages;
		$result[1] = $total;
		return $result;
	}
// Get All End

// Store Code Start
	function storeEmployerPackage()
	{
		$row = & $this->getTable('employerpackage');

		$data = JRequest :: get('post');

		if(! isset($this->_config)){
			$this->getConfig('');
		}
		foreach ($this->_config as $conf){
				if ($conf->configname == 'date_format') $dateformat = $conf->configvalue;
		}
		if($dateformat == 'm-d-Y'){
			$arr = explode('-', $data['discountstartdate']);
			$data['discountstartdate'] =  $arr[2].'-'.$arr[0].'-'.$arr[1];
			$arr = explode('-', $data['discountenddate']);
			$data['discountenddate'] =  $arr[2].'-'.$arr[0].'-'.$arr[1];
		}elseif($dateformat == 'd-m-Y'){
			$arr = explode('-', $data['discountstartdate']);
			$data['discountstartdate'] =  $arr[2].'-'.$arr[1].'-'.$arr[0];
			$arr = explode('-', $data['discountenddate']);
			$data['discountenddate'] =  $arr[2].'-'.$arr[1].'-'.$arr[0];
		}

		$data['discountstartdate'] =  date('Y-m-d H:i:s',strtotime($data['discountstartdate']));
		$data['discountenddate'] =  date('Y-m-d H:i:s',strtotime($data['discountenddate']));
		if (!$row->bind($data))	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			echo $this->_db->getErrorMsg();
			return false;
		}
		return true;
	}
	function storeJobSeekerPackage()
	{
		$row = & $this->getTable('jobseekerpackage');

		$data = JRequest :: get('post');

		if(! isset($this->_config)){
			$this->getConfig('');
		}
		foreach ($this->_config as $conf){
				if ($conf->configname == 'date_format') $dateformat = $conf->configvalue;
		}
		if($dateformat == 'm-d-Y'){
			$arr = explode('-', $data['discountstartdate']);
			$data['discountstartdate'] =  $arr[2].'-'.$arr[0].'-'.$arr[1];
			$arr = explode('-', $data['discountenddate']);
			$data['discountenddate'] =  $arr[2].'-'.$arr[0].'-'.$arr[1];
		}elseif($dateformat == 'd-m-Y'){
			$arr = explode('-', $data['discountstartdate']);
			$data['discountstartdate'] =  $arr[2].'-'.$arr[1].'-'.$arr[0];
			$arr = explode('-', $data['discountenddate']);
			$data['discountenddate'] =  $arr[2].'-'.$arr[1].'-'.$arr[0];
		}

		$data['discountstartdate'] =  date('Y-m-d H:i:s',strtotime($data['discountstartdate']));
		$data['discountenddate'] =  date('Y-m-d H:i:s',strtotime($data['discountenddate']));
		

		if (!$row->bind($data))	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			echo $this->_db->getErrorMsg();
			return false;
		}
		return true;
	}

	function storeDepartment()
	{
		global $resumedata;
		$row = &$this->getTable('department');
		$data = JRequest :: get('post');

		if (!$row->bind($data)){
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		if (!$row->check())	{
			$this->setError($this->_db->getErrorMsg());
			return 2;
		}
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			echo $this->_db->getErrorMsg();
			return false;
		}
		return true;
	}


	function storeCompany() //store company
	{
		$row = &$this->getTable('company');
		$data = JRequest :: get('post');

		if ( !$this->_config )
			$this->getConfig('');

		foreach ($this->_config as $conf){
			if ($conf->configname == 'date_format') $dateformat = $conf->configvalue;
		}
		
		if($dateformat == 'm-d-Y'){
			$arr = explode('-', $data['since']);
			$data['since'] =  $arr[2].'-'.$arr[0].'-'.$arr[1];
		}elseif($dateformat == 'd-m-Y'){
			$arr = explode('-', $data['since']);
			$data['since'] =  $arr[2].'-'.$arr[1].'-'.$arr[0];
		}
		$data['since'] =  date('Y-m-d H:i:s',strtotime($data['since']));

		if ( !$this->_comp_editor )
			$this->getConfig();
		if ($this->_comp_editor == 1){
			$data['description'] = JRequest::getVar('description', '', 'post', 'string', JREQUEST_ALLOWRAW);
		}
		$returnvalue = 1;

		// For database
		if($_FILES['logo']['size'] > 0){ // logo
			$data['logofilename'] = $_FILES['logo']['name']; // file name
			$data['logoisfile'] = 1; // logo store in file system
		}
		if($data['deletelogo'] == 1){ // delete logo
			$data['logofilename'] = ''; // file name
			$data['logoisfile'] = -1; // no logo
		}

		if($_FILES['smalllogo']['size'] > 0){ //small logo
			$data['smalllogofilename'] = $_FILES['smalllogo']['name']; // file name
			$data['smalllogoisfile'] = 1; // logo store in file system
		}
		if($data['deletesmalllogo'] == 1){ //delete small logo
			$data['smalllogofilename'] = ''; // file name
			$data['smalllogoisfile'] = -1; // no logo
		}

		if($_FILES['aboutcompany']['size'] > 0){ //about company
			$data['aboutcompanyfilename'] = $_FILES['aboutcompany']['name']; // file name
			$data['aboutcompanyisfile'] = 1; // logo store in file system
		}
		if($data['deleteaboutcompany'] == 1){ // delete about company
			$data['aboutcompanyfilename'] = ''; // file name
			$data['aboutcompanyisfile'] = -1; // no logo
		}


		if (!$row->bind($data))	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		if (!$row->check())	{
			$this->setError($this->_db->getErrorMsg());
			return 2;
		}
//		echo '<br> 4';
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}

		$this->storeUserFieldData($data, $row->id);


		// For file upload
		$companyid = $row->id;
		if($_FILES['logo']['size'] > 0){ // logo
			$returnvalue = $this->uploadFile($companyid, 1, 0);
		}
		if($data['deletelogo'] == 1){ // delete logo
			$returnvalue = $this->uploadFile($companyid, 1, 1);
		}

		if($_FILES['smalllogo']['size'] > 0){ //small logo
			$returnvalue = $this->uploadFile($companyid, 2, 0);
		}
		if($data['deletesmalllogo'] == 1){ //delete small logo
			$returnvalue = $this->uploadFile($companyid, 2, 1);
		}

		if($_FILES['aboutcompany']['size'] > 0){ //about company
			$returnvalue = $this->uploadFile($companyid, 3, 0);
		}
		if($data['deleteaboutcompany'] == 1){ // delete about company
			$returnvalue = $this->uploadFile($companyid, 3, 1);
		}

		//if ($returnvalue != 1)
			return $returnvalue;
	}

	function storeFolder() //store folder
	{
		$row = &$this->getTable('folder');
		$data = JRequest :: get('post');
		$data['decription'] = JRequest::getVar('decription', '', 'post', 'string', JREQUEST_ALLOWRAW);
		$name =$data['name'] ;
                if($this->folderValidation($name)) return 3;
                $returnvalue = 1;
                    if (!$row->bind($data))	{
                            $this->setError($this->_db->getErrorMsg());
                            return false;
                    }
                    if (!$row->check())	{
                            $this->setError($this->_db->getErrorMsg());
                            return 2;
                    }
    //		echo '<br> 4';
                    if (!$row->store())	{
                            $this->setError($this->_db->getErrorMsg());
                            return false;
                    }
                	return $returnvalue;
	}
        function folderValidation($foldername){
            $db = & JFactory:: getDBO();
            $query = "SELECT COUNT(id) FROM #__wrecruit_folders
            WHERE name = ". $db->Quote($foldername);
            $db->setQuery( $query );
            $result = $db->loadResult();
            //echo '<br>'.$query;
            if($result > 0)  return true ;
			else return false;
        }
	function storeJob() //store job
	{
		$row = &$this->getTable('job');
		$data = JRequest :: get('post');
		
		if (isset($this_config) == false)
			$this->getConfig('');
			foreach ($this->_config as $conf){
				if ($conf->configname == 'date_format') $dateformat = $conf->configvalue;
			}
			if($dateformat == 'm-d-Y'){
				$arr = explode('-', $data['startpublishing']);
				$data['startpublishing'] =  $arr[2].'-'.$arr[0].'-'.$arr[1];
				$arr = explode('-', $data['stoppublishing']);
				$data['stoppublishing'] =  $arr[2].'-'.$arr[0].'-'.$arr[1];
			}elseif($dateformat == 'd-m-Y'){
				$arr = explode('-', $data['startpublishing']);
				$data['startpublishing'] =  $arr[2].'-'.$arr[1].'-'.$arr[0];
				$arr = explode('-', $data['stoppublishing']);
				$data['stoppublishing'] =  $arr[2].'-'.$arr[1].'-'.$arr[0];
			}
		$data['startpublishing'] =  date('Y-m-d H:i:s',strtotime($data['startpublishing']));
		$data['stoppublishing'] =  date('Y-m-d H:i:s',strtotime($data['stoppublishing']));


		if ($this->_job_editor == 1){
			$data['description'] = JRequest::getVar('description', '', 'post', 'string', JREQUEST_ALLOWRAW);
			$data['qualifications'] = JRequest::getVar('qualifications', '', 'post', 'string', JREQUEST_ALLOWRAW);
			$data['prefferdskills'] = JRequest::getVar('prefferdskills', '', 'post', 'string', JREQUEST_ALLOWRAW);
			$data['agreement'] = JRequest::getVar('agreement', '', 'post', 'string', JREQUEST_ALLOWRAW);
		}
		//echo '<br> try to bind';
		if (!$row->bind($data))
		{
			$this->setError($this->_db->getErrorMsg());
			echo $this->_db->getErrorMsg();
			return false;
		}

		//echo '<br> try to check';
		$check_return = $row->check();

		if ($check_return != 1)
		{
			$this->setError($this->_db->getErrorMsg());
			return $check_return;
		}

		//echo '<br> try to store';
		if (!$row->store())
		{
			$this->setError($this->_db->getErrorMsg());
			echo $this->_db->getErrorMsg();
			return false;
		}

		$this->storeUserFieldData($data, $row->id);

		return true;
	}

	function storeUserFieldData($data, $refid) //store  user field data
	{
		if($refid) if (is_numeric($refid) == false) return false;
		$row = &$this->getTable('userfielddata');
		for($i = 1; $i <= $data['userfields_total']; $i++){
			$fname = "userfields_".$i;
			$fid = "userfields_".$i."_id";
			$dataid = "userdata_".$i."_id";
			//$fielddata['id'] = "";

			$fielddata['id'] = $data[$dataid];
			$fielddata['referenceid'] = $refid;
			$fielddata['field'] = $data[$fid];
			$fielddata['data'] = $data[$fname];

			if (!$row->bind($fielddata))	{
				$this->setError($this->_db->getErrorMsg());
				return false;
			}
			if (!$row->store())	{
				$this->setError($this->_db->getErrorMsg());
				echo $this->_db->getErrorMsg();
				return false;
			}
		}
		return true;
	}

	function storeShortListCandidate($uid,$resumeid,$jobid){
		if (is_numeric($resumeid) == false) return false;
		if (is_numeric($jobid) == false) return false;
		if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
                if ($this->shortListCandidateValidation($uid,$jobid,$resumeid) == false) return 3;
                
                $row = &$this->getTable('shortlistcandidate');
                $row->uid = $uid;
                $row->jobid = $jobid;
                $row->cvid = $resumeid;
                $row->status = 1;
                $row->created = date('Y-m-d H:i:s');

		if (!$row->check())	{
			$this->setError($this->_db->getErrorMsg());
			return 2;
		}
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			echo $this->_db->getErrorMsg();
			return false;
		}
		return true;
	}
	function shortListCandidateValidation($uid, $jobid, $resumeid)
	{
		if($uid) if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		if (is_numeric($jobid) == false) return false;
		if (is_numeric($resumeid) == false) return false;
		$db =& JFactory::getDBO();
		$query = "SELECT COUNT(id) FROM #__wrecruit_shortlistcandidates
		WHERE jobid = ".$jobid." AND cvid = ".$resumeid;
		$db->setQuery( $query );
		$result = $db->loadResult();
		if ($result == 0) return true; else return false;
	}


	function storeResume()
	{
		$row = & $this->getTable('resume');

		$data = JRequest :: get('post');

		if ( !$this->_config )
			$this->getConfig('');
		foreach ($this->_config as $conf){
			if ($conf->configname == 'date_format') $dateformat = $conf->configvalue;
		}

		if($dateformat == 'm-d-Y'){
			$arr = explode('-', $data['date_start']);
			$data['date_start'] =  $arr[2].'-'.$arr[0].'-'.$arr[1];
		}elseif($dateformat == 'd-m-Y'){
			$arr = explode('-', $data['date_start']);
			$data['date_start'] =  $arr[2].'-'.$arr[1].'-'.$arr[0];
		}
	 
		$data['date_start'] =  date('Y-m-d H:i:s',strtotime($data['date_start']));	
		
		$data['resume'] = JRequest::getVar('resume', '', 'post', 'string', JREQUEST_ALLOWRAW);
//		$returnvalue = $this->uploadResume($resumedata['uid']);

		if($_FILES['resumefile']['size'] > 0){
			$file_name = $_FILES['resumefile']['name']; // file name
			$data['filename'] = $file_name;
			$data['filecontent'] = '';
		}else {
			if ($data['deleteresumefile'] == 1){
				$data['filename'] = '';
				$data['filecontent'] = '';

			}
		}

		if($_FILES['photo']['size'] > 0){
			$file_name = $_FILES['photo']['name']; // file name
			$data['photo'] = $file_name;
		}else {
			if ($data['deleteresumefile'] == 1){
				$data['photo'] = '';
			}
		}

/*
		if($_FILES['resumefile']['size'] > 0)
		{
			$fileName = $_FILES['resumefile']['name'];
			$tmpName  = $_FILES['resumefile']['tmp_name'];
			$fileSize = $_FILES['resumefile']['size'];
			$fileType = $_FILES['resumefile']['type'];


			$fp      = fopen($tmpName, 'r');
			$content = fread($fp, filesize($tmpName));
			$content = addslashes($content);
			fclose($fp);

			if(!get_magic_quotes_gpc())
			{
			    $fileName = addslashes($fileName);
			}
		}
		$data['filename'] = $fileName;
		$data['filetype'] = $fileType;
		$data['filesize'] = $fileSize;
		$data['filecontent'] = $content;
*/

		if (!$row->bind($data))
		{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		if (!$row->check())
		{
			$this->setError($this->_db->getErrorMsg());
			return 2;
		}
		if (!$row->store())
		{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}

		$resumereturnvalue = $this->uploadResume($row->id);
		if($resumereturnvalue != 1){
			$resumedeletedata['id'] = $row->id;		
			$resumedeletedata['filename'] = '';
			$row->bind($resumedeletedata);
			$row->store();
		}
		$returnvalue = $this->uploadPhoto($row->id);
		return $resumereturnvalue;

	}

	function uploadResume($id)
	{
		if (is_numeric($id) == false) return false;
		global $resumedata ;
		$db =& JFactory::getDBO();
		$str=JPATH_BASE;
		$base = substr($str, 0,strlen($str)-14); //remove administrator
		$resumequery = "SELECT * FROM ".$db->nameQuote('#__wrecruit_resume') ."
		WHERE uid = ".$db->Quote($u_id);
		//echo '<br>sql '.$resumequery;
		$iddir = 'resume_'.$id;
                if(! isset($this->_config)) $this->getConfig();
                foreach ($this->_config as $conf){
                        if ($conf->configname == 'data_directory') $datadirectory = $conf->configvalue;
                }
                $path =$base.'/'.$datadirectory;

		if($_FILES['resumefile']['size'] > 0){
			$file_name = $_FILES['resumefile']['name']; // file name
			$file_tmp = $_FILES['resumefile']['tmp_name']; // actual location
			$file_size = $_FILES['resumefile']['size']; // file size
			$file_type = $_FILES['resumefile']['type']; // mime type of file determined by php
			$file_error = $_FILES['resumefile']['error']; // any error!. get reason here

			if( !empty($file_tmp)){	// only MS office and text file is accepted.
				$ext = $this->getExtension($file_name);
				if (($ext != "txt") && ($ext != "doc") && ($ext != "docx") && ($ext != "pdf"))
					return 6; //file type mistmathc
/*
				if( !(($file_type=="application/msword") || ($file_type=="text/plain")) )
				{
					return 6; //file type mistmathc
				}
*/			}

			//$path =$base.'/components/com_wrecruit/data/jobseeker';
			if (!file_exists($path)){ // creating main directory
				mkdir($path, 0755);
			}
			$path =$path.'/data';
			if (!file_exists($path)){ // creating data directory
				mkdir($path, 0755);
			}
			$path =$path.'/jobseeker';
			if (!file_exists($path)){ // creating jobseeker directory
				mkdir($path, 0755);
			}
			$userpath= $path . '/'.$iddir;
			if (!file_exists($userpath)){ // create user directory
				mkdir($userpath, 0755);
			}
			$userpath= $path . '/'.$iddir.'/resume';
			if (!file_exists($userpath)){ // create user directory
				mkdir($userpath, 0755);
			}
			$files = glob($userpath.'/*.*');
			array_map('unlink', $files);  //delete all file in user directory

			move_uploaded_file($file_tmp, $userpath.'/' . $file_name);
			//unlink($file_tmp);

//			$resumedata['filename'] = $file_name;
//			$resumedata['filecontent'] = '';
			return 1;
		}else {
			if ($resumedata['deleteresumefile'] == 1){
				$path =$path.'/data/jobseeker';
				$userpath= $path . '/'.$iddir.'/resume';
				$files = glob($userpath.'/*.*');
				array_map('unlink', $files);
				$resumedata['filename'] = '';
				$resumedata['filecontent'] = '';
			}else{
//				$db->setQuery( $resumequery );
//				$resume = $db->loadObject();
//				if ( isset($resume) ){ // if already file upload then pick the path
//						$resumedata['filename'] = $resume->filename;
//						$resumedata['filecontent'] = '';
//				}
			}
			return 1;
		}

	}


	function uploadPhoto($id)
	{
		if (is_numeric($id) == false) return false;
		global $resumedata ;
		$db =& JFactory::getDBO();
		$str=JPATH_BASE;
		$base = substr($str, 0,strlen($str)-14); //remove administrator
                if(! isset($this->_config)) $this->getConfig();
                foreach ($this->_config as $conf){
                        if ($conf->configname == 'data_directory') $datadirectory = $conf->configvalue;
                }
                $path =$base.'/'.$datadirectory;

		$resumequery = "SELECT * FROM ".$db->nameQuote('#__wrecruit_resume') ."
		WHERE uid = ".$db->Quote($u_id);
		//echo '<br>sql '.$resumequery;
		$iddir = 'resume_'.$id;
		if($_FILES['photo']['size'] > 0){
			$file_name = $_FILES['photo']['name']; // file name
			$file_tmp = $_FILES['photo']['tmp_name']; // actual location
			$file_size = $_FILES['photo']['size']; // file size
			$file_type = $_FILES['photo']['type']; // mime type of file determined by php
			$file_error = $_FILES['photo']['error']; // any error!. get reason here

			if( !empty($file_tmp)){
				$ext = $this->getExtension($file_name);
				if (($ext != "gif") && ($ext != "jpg") && ($ext != "jpeg") && ($ext != "png"))
					return 6; //file type mistmathc
			}

			//$path =$base.'/components/com_wrecruit/data/jobseeker';
			if (!file_exists($path)){ // creating main directory
				mkdir($path, 0755);
			}
			$path =$path.'/data';
			if (!file_exists($path)){ // creating data directory
				mkdir($path, 0755);
			}
			$path =$path.'/jobseeker';
			if (!file_exists($path)){ // creating jobseeker directory
				mkdir($path, 0755);
			}
			$userpath= $path . '/'.$iddir;
			if (!file_exists($userpath)){ // create user directory
				mkdir($userpath, 0755);
			}
			$userpath= $path . '/'.$iddir.'/photo';
			if (!file_exists($userpath)){ // create user directory
				mkdir($userpath, 0755);
			}
			$files = glob($userpath.'/*.*');
			array_map('unlink', $files);  //delete all file in user directory

			move_uploaded_file($file_tmp, $userpath.'/' . $file_name);
			//unlink($file_tmp);

//			$resumedata['photo'] = $file_name;
			return 1;
		}else {
			if ($resumedata['deleteresumefile'] == 1){
				$path =$path.'/data/jobseeker';
				$userpath= $path . '/'.$iddir.'/photo';
				$files = glob($userpath.'/*.*');
				array_map('unlink', $files);
				$resumedata['photo'] = '';
			}else{
//				$db->setQuery( $resumequery );
//				$resume = $db->loadObject();
//				if ( isset($resume) ){ // if already file upload then pick the path
//						$resumedata['photo'] = $resume->filename;
//				}
			}
			return 1;
		}

	}

	function storeCategory()
	{
		$row = & $this->getTable('category');

		$data = JRequest :: get('post');
		if (!$row->bind($data))
		{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		if (!$row->check())
		{
			$this->setError($this->_db->getErrorMsg());
			return 2;
		}
		if ($data['id'] == ''){ // only for new
			$result=$this->isCategoryExist($data['cat_title']);
			if ($result == true)
			{
				//echo '<br> cat exist';
				return 3;
			}
		}
		if (!$row->store())
		{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}

		return true;

	}

	function storeSubCategory()
	{
		$row = & $this->getTable('subcategory');

		$data = JRequest :: get('post');
		if (!$row->bind($data))
		{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		if (!$row->check())
		{
			$this->setError($this->_db->getErrorMsg());
			return 2;
		}
		if ($data['id'] == ''){ // only for new
			$result=$this->isSubCategoryExist($data['title']);
			if ($result == true) return 3;
		}
		if (!$row->store()){
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		return true;
	}

        function categoryChangeStatus($id, $status)
	{
		if (is_numeric($id) == false) return false;
		if (is_numeric($status) == false) return false;

                $row = & $this->getTable('category');
                $row->id = $id;
                $row->isactive = $status;
		if (!$row->store()){
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		return true;
	}

        function subCategoryChangeStatus($id, $status)
	{
		if (is_numeric($id) == false) return false;
		if (is_numeric($status) == false) return false;

                $row = & $this->getTable('subcategory');
                $row->id = $id;
                $row->status = $status;
		if (!$row->store()){
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		return true;
	}
        function messageChangeStatus($id, $status)
	{
		if (is_numeric($id) == false) return false;
		if (is_numeric($status) == false) return false;

                $row = & $this->getTable('message');
                $row->id = $id;
                $row->status = $status;
		if (!$row->store()){
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		return true;
	}
        function folderChangeStatus($id, $status)
	{
		if (is_numeric($id) == false) return false;
		if (is_numeric($status) == false) return false;

                $row = & $this->getTable('folder');
                $row->id = $id;
                $row->status = $status;
		if (!$row->store()){
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		return true;
	}

	function storeJobType()
	{
		$row = & $this->getTable('jobtype');

		$data = JRequest :: get('post');
		if (!$row->bind($data))	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		return true;
	}
	function storeAges()
	{
		$row = & $this->getTable('ages');

		$data = JRequest :: get('post');
		if (!$row->bind($data))	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		return true;
	}
	function storeCurrency()
	{
		$row = & $this->getTable('currency');

		$data = JRequest :: get('post');
		if (!$row->bind($data))	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		return true;
	}

	function storeCareerLevel()
	{
		$row = & $this->getTable('careerlevel');

		$data = JRequest :: get('post');
		if (!$row->bind($data))	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		return true;
	}
	function storeExperience()
	{
		$row = & $this->getTable('experience');

		$data = JRequest :: get('post');
		if (!$row->bind($data))	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		return true;
	}
	function storeSalaryRangeType()
	{
		$row = & $this->getTable('salaryrangetype');

		$data = JRequest :: get('post');
		if (!$row->bind($data))	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		return true;
	}

	function storeJobStatus()
	{
		$row = & $this->getTable('jobstatus');

		$data = JRequest :: get('post');
		if (!$row->bind($data))	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		return true;
	}

	function storeShift()
	{
		$row = & $this->getTable('shift');

		$data = JRequest :: get('post');
		if (!$row->bind($data))	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		return true;
	}

	function storeHighestEducation()
	{
		$row = & $this->getTable('highesteducation');

		$data = JRequest :: get('post');
		if (!$row->bind($data))	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		return true;
	}

	function storeSalaryRange()
	{
		$row = & $this->getTable('salaryrange');

		$data = JRequest :: get('post');
		if (!$row->bind($data))
		{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		if (!$row->check())
		{
			$this->setError($this->_db->getErrorMsg());
			return 2;
		}
		if ($data['id'] == ''){ // only for new
//			$result=$this->SalaryRangeValidations($data['cat_title']);
			if ($result == true)
			{
				//echo '<br> cat exist';
				return 3;
			}
		}
		if (!$row->store())
		{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}

		return true;

	}

	function storeRole()
	{
		$row = & $this->getTable('role');

		$data = JRequest :: get('post');
		if (!$row->bind($data))	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		if (!$row->check())	{
			$this->setError($this->_db->getErrorMsg());
			return 2;
		}
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}

		return true;

	}

	function storeUserRole()
	{
		$row = & $this->getTable('userrole');

		$data = JRequest :: get('post');
		if (!$row->bind($data))	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		if (!$row->check())	{
			$this->setError($this->_db->getErrorMsg());
			return 2;
		}
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}

		return true;

	}

	function storeResumeUserFields()
	{

		$db =& JFactory::getDBO();

		$data = JRequest :: get('post');

		$fieldvaluerow = & $this->getTable('fieldsordering');

		$userfields = $data['userfield'];
		$titles = $data['title'];
		$publisheds = $data['published'];
		$requireds = $data['required'];
		$id = $data['id'];
		for ($i=0; $i <= 9;$i++) {

			$fieldvaluedata = array();
			$fieldvaluedata['id'] = $id[$i];
			$fieldvaluedata['field'] = $userfields[$i];;
			$fieldvaluedata['fieldtitle'] = $titles[$i];
			$fieldvaluedata['ordering'] = 21+$i;
			$fieldvaluedata['section'] = 1000;
			$fieldvaluedata['fieldfor'] = 3;
			$fieldvaluedata['published'] = $publisheds[$i];
			$fieldvaluedata['sys'] = 0;
			$fieldvaluedata['cannotunpublish'] = 0;
			$fieldvaluedata['required'] = $requireds[$i];
			
			if (!$fieldvaluerow->bind($fieldvaluedata))	{
				$this->setError($this->_db->getErrorMsg());
				//echo $this->_db->getErrorMsg();
				return false;
			}
			if (!$fieldvaluerow->store())	{
				$this->setError($this->_db->getErrorMsg());
				//echo $this->_db->getErrorMsg();
				return false;
			}
			
		}
			
		return true;

	}
	function storeUserField()
	{
		echo '<br> store user field';

		$db =& JFactory::getDBO();
		$row = & $this->getTable('userfield');

		$data = JRequest :: get('post');

		if (!$row->bind($data))	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		if (!$row->check()) {
			$this->setError($this->_db->getErrorMsg());
			return 2;
		}
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		// add in field ordering
		if ($data['id'] == '') { // only for new
			$query ="INSERT INTO #__wrecruit_fieldsordering
					(field, fieldtitle, ordering, section, fieldfor, published, sys, cannotunpublish)
					VALUES(". $row->id .",'". $data['title'] ."', ( SELECT max(ordering)+1 FROM #__wrecruit_fieldsordering AS field WHERE fieldfor = " . $data['fieldfor'] . "), ''
					, " . $data['fieldfor'] . "," . $data['published'] . " ,0,0)
			";
			//echo '<br>sql '.$query;
			$db->setQuery( $query );
			if (!$db->query()) {
				return false;
			}
		}

		// store values
		$names = $data['jsNames'];
		$values = $data['jsValues'];
		$fieldvaluerow = & $this->getTable('userfieldvalue');

		for ($i=0; $i <= $data['valueCount'];$i++) {

			$fieldvaluedata = array();
			$fieldvaluedata['id'] = '';
			$fieldvaluedata['field'] = $row ->id;
			$fieldvaluedata['fieldtitle'] = $names[$i];
			$fieldvaluedata['fieldvalue'] = $values[$i];
			$fieldvaluedata['ordering'] = $i + 1;
			$fieldvaluedata['sys'] = 0;

			if (!$fieldvaluerow->bind($fieldvaluedata))	{
				$this->setError($this->_db->getErrorMsg());
				return false;
			}
			if (!$fieldvaluerow->store())	{
				$this->setError($this->_db->getErrorMsg());
				return false;
			}
			echo '<br>name '.$names[$i];
			echo '<br>value '.$values[$i];

		}

		return true;

	}

	function storeConfig()
	{
		$row = & $this->getTable('config');

		$data = JRequest :: get('post');
		$config = array();

                foreach ($data as $key=>$value){
                        //echo "<br>".$key;
                        //echo $value;
                        $config['configname'] = $key;
                        $config['configvalue'] = $value;
                        //echo 'config'.$config['configname'];
                        if (!$row->bind($config)){	$this->setError($this->_db->getErrorMsg());	return false;	}
                        if (!$row->store())	{	$this->setError($this->_db->getErrorMsg());	return false;	}
		   }

		return true;

	}

	function storeEmailTemplate()
	{
		$row = & $this->getTable('emailtemplate');

		$data = JRequest :: get('post');
		$data['body'] = JRequest::getVar('body', '', 'post', 'string', JREQUEST_ALLOWRAW);

		if (!$row->bind($data))	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}

		return true;

	}

	function storeCountry()
	{
		$row = & $this->getTable('country');

		$data = JRequest :: get('post');
		if (!$data['id']){ // only for new
			$existvalue = $this->isCountryExist($data['name']);
			if ($existvalue == true) return 3;
			$returnvalue = $this->makeCountryCode($data['name']);
			if ($returnvalue == false) return false;
			else $code = $returnvalue;
		}
		if (!$row->bind($data))	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		if (!$data['id'])	$row->code = $code;
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}

		return true;

	}

	function storeState()
	{
		$row = & $this->getTable('state');

		$data = JRequest :: get('post');
		if (!$data['id']){ // only for new
			$existvalue = $this->isStateExist($data['name'], $data['countrycode']);
			if ($existvalue == true) return 3;
			$returnvalue = $this->makeStateCode($data['name'], $data['countrycode']);
			if ($returnvalue == false) return false;
			else $code = $returnvalue;
		}
		if (!$row->bind($data))	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		if (!$data['id'])	$row->code = $code;
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		return true;
	}
	function storeCounty()
	{
		$row = & $this->getTable('county');

		$data = JRequest :: get('post');
		if (!$data['id']){ // only for new
			$existvalue = $this->isCountyExist($data['name'], $data['statecode']);
			if ($existvalue == true) return 3;
			$returnvalue = $this->makeCountyCode($data['name'], $data['statecode']);
			if ($returnvalue == false) return false;
			else $code = $returnvalue;
		}
		if (!$row->bind($data))	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		if (!$data['id'])	$row->code = $code;
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		return true;
	}
	function storeCity()
	{
		$row = & $this->getTable('city');

		$data = JRequest :: get('post');
		if (!$data['id']){ // only for new
			$existvalue = $this->isCityExist($data['name'], $data['countycode']);
			if ($existvalue == true) return 3;
			$returnvalue = $this->makeCityCode($data['name'], $data['countycode']);
			if ($returnvalue == false) return false;
			else $code = $returnvalue;
		}
		if (!$row->bind($data))	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		if (!$data['id'])	$row->code = $code;
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		return true;
	}
/* zain*/
        function storeMessage($uid,$cid)
	{
		if ($uid) if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		if($cid) if ((is_numeric($cid) == false) || ($cid == 0) || ($cid == '')) return false;
		$data = JRequest :: get('post');
                $row = &$this->getTable('message');
                $data['status'] = 1;
		if (!$row->bind($data)){
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
                $row->sendby = $uid;
		if (!$row->check())	{
			$this->setError($this->_db->getErrorMsg());
			return 2;
		}
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			echo $this->_db->getErrorMsg();
			return false;
		}
                if ($row->status == 1) return true;
                elseif ($row->status == 0) return 2;
	}


/* zain*/
// Store Code End

// Delete Code Start
/* zain*/
        function deleteFolder()//delete Messages
	{
		$cids = JRequest :: getVar('cid', array (0), 'post', 'array');
		$row = & $this->getTable('folder');
		$deleteall = 1;
		foreach ($cids as $cid)	{
			if($this->folderCanDelete($cid) == true){

				if (!$row->delete($cid)){
					$this->setError($row->getErrorMsg());
					return false;
				}
			}else $deleteall++ ;
		}
		return $deleteall;
	}

	function folderCanDelete($id){
		if (is_numeric($id) == false) return false;
		$db = &$this->getDBO();

		$query = "SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_folders')." WHERE  = ". $id ."

					AS total ";
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$total = $db->loadResult();

		if ($total > 0)
			return false;
		else
			return true;
	}
        function deleteMessages()//delete Messages
	{
		$cids = JRequest :: getVar('cid', array (0), 'post', 'array');
		$row = & $this->getTable('message');
		$deleteall = 1;
		foreach ($cids as $cid)	{
			if($this->messageCanDelete($cid) == true){

				if (!$row->delete($cid)){
					$this->setError($row->getErrorMsg());
					return false;
				}
			}else $deleteall++ ;
		}
		return $deleteall;
	}

	function messageCanDelete($id){
		if (is_numeric($id) == false) return false;
		$db = &$this->getDBO();

		$query = "SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_message')." WHERE  = ". $id ."

					AS total ";
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$total = $db->loadResult();

		if ($total > 0)
			return false;
		else
			return true;
	}
/* zain */
        function deleteEmployerPackage()//delete employer package
	{
		$cids = JRequest :: getVar('cid', array (0), 'post', 'array');
		$row = & $this->getTable('employerpackage');
		$deleteall = 1;
		foreach ($cids as $cid)	{
			if($this->employerPackageCanDelete($cid) == true){

				if (!$row->delete($cid)){
					$this->setError($row->getErrorMsg());
					return false;
				}
			}else $deleteall++ ;
		}
		return $deleteall;
	}

	function employerPackageCanDelete($id){
		if (is_numeric($id) == false) return false;
		$db = &$this->getDBO();

		$query = "SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_employerpaymenthistory')." WHERE packageid = ". $id ."

					AS total ";
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$total = $db->loadResult();

		if ($total > 0)
			return false;
		else
			return true;
	}
	function deleteCompany()
	{
		$cids = JRequest :: getVar('cid', array (0), 'post', 'array');
		$row = & $this->getTable('company');
		$deleteall = 1;
		foreach ($cids as $cid)	{
			if($this->companyCanDelete($cid) == true){
				if (!$row->delete($cid)){
					$this->setError($row->getErrorMsg());
					return false;
				}
			}else $deleteall++ ;
		}
		return $deleteall;
	}





	function deleteDepartment()
	{
		$cids = JRequest :: getVar('cid', array (0), 'post', 'array');
		$row = & $this->getTable('department');
		$deleteall = 1;
		foreach ($cids as $cid)	{
			if($this->departmentCanDelete($cid) == true){
				if (!$row->delete($cid)){
					$this->setError($row->getErrorMsg());
					return false;
				}
			}else $deleteall++ ;
		}
		return $deleteall;
	}

	function deleteJob()
	{
		$cids = JRequest :: getVar('cid', array (0), 'post', 'array');
		$row = & $this->getTable('job');
		$deleteall = 1;
		foreach ($cids as $cid)	{
			if($this->jobCanDelete($cid) == true){
				if (!$row->delete($cid)){
					$this->setError($row->getErrorMsg());
					return false;
				}
			}else $deleteall++ ;
		}
		return $deleteall;
	}

	function deleteResume()
	{
		$cids = JRequest :: getVar('cid', array (0), 'post', 'array');
		$row = & $this->getTable('resume');
		$deleteall = 1;
		foreach ($cids as $cid)	{
			if($this->resumeCanDelete($cid) == true){
				if (!$row->delete($cid)){
					$this->setError($row->getErrorMsg());
					return false;
				}
			}else $deleteall++ ;
		}
		return $deleteall;
	}

	function deleteEmpApp()
	{
		$cids = JRequest :: getVar('cid', array (
			0
		), 'post', 'array');
		$row = & $this->getTable('empapp');

		foreach ($cids as $cid)
		{
			if (!$row->delete($cid))
			{
				$this->setError($row->getErrorMsg());
				return false;
			}
		}

		return true;
	}

	function deleteCategory()
	{
		$cids = JRequest :: getVar('cid', array (0), 'post', 'array');
		$row = & $this->getTable('category');
		$deleteall = 1;
		foreach ($cids as $cid)	{
			if($this->categoryCanDelete($cid) == true){
				if (!$row->delete($cid)){
					$this->setError($row->getErrorMsg());
					return false;
				}
			}else $deleteall++ ;
		}
		return $deleteall;
	}

	function deleteSubCategory()
	{
		$cids = JRequest :: getVar('cid', array (0), 'post', 'array');
		$row = & $this->getTable('subcategory');
		$deleteall = 1;
		foreach ($cids as $cid)	{
			if($this->subCategoryCanDelete($cid) == true){
				if (!$row->delete($cid)){
					$this->setError($row->getErrorMsg());
					return false;
				}
			}else $deleteall++ ;
		}
		return $deleteall;
	}
	function deleteCategoryAndSubcategory()
	{
		
		$db = &$this->getDBO();
		$cids = JRequest :: getVar('cid', array (0), 'post', 'array');
		$row = & $this->getTable('category');
		$row1 = & $this->getTable('subcategory');
		$deleteall = 1;
		foreach ($cids as $cid)	{
			if($this->checkCategoryCanDelete($cid) == true){
				$query = "SELECT id FROM ".$db->nameQuote('#__wrecruit_subcategories')." WHERE categoryid  = ".$cid;
				//echo '<br> SQL '.$query;
				$db->setQuery($query);
				$subcategory = $db->loadObjectList();
				foreach ($subcategory as $subcat){
					if($this->subCategoryCanDelete($subcat->id) == true){
						if (!$row1->delete($subcat->id)){
							$this->setError($row1->getErrorMsg());
							return false;
						}
					
				    }
				}
				if (!$row->delete($cid)){
					$this->setError($row->getErrorMsg());
					return false;
				}
			}else $deleteall++ ;
		}
		return $deleteall;
	}
		function checkCategoryCanDelete($categoryid){		// for delete category and subcategory
			if (is_numeric($categoryid) == false) return false;
			$db = &$this->getDBO();

			$query = "SELECT
						( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_companies')." WHERE category = ". $categoryid .")
						+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_jobs')." WHERE jobcategory = ". $categoryid .")
						+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE job_category = ". $categoryid .")
						AS total ";
			//echo '<br> SQL '.$query;
			$db->setQuery($query);
			$total = $db->loadResult();
			//echo $total; die();
			if ($total > 0)
				return false;
			else
				return true;
	}


	function deleteJobType()
	{
		$cids = JRequest :: getVar('cid', array (0), 'post', 'array');
		$row = & $this->getTable('jobtype');
		$deleteall = 1;
		foreach ($cids as $cid)	{
			if($this->jobTypeCanDelete($cid) == true){
				if (!$row->delete($cid)){
					$this->setError($row->getErrorMsg());
					return false;
				}
			}else $deleteall++ ;
		}
		return $deleteall;
	}
	function deleteAge()
	{
		$cids = JRequest :: getVar('cid', array (0), 'post', 'array');
		$row = & $this->getTable('ages');
		$deleteall = 1;
		foreach ($cids as $cid)	{
			if($this->ageCanDelete($cid) == true){
				if (!$row->delete($cid)){
					$this->setError($row->getErrorMsg());
					return false;
				}
			}else $deleteall++ ;
		}
		return $deleteall;
	}
	function deleteCurrency()
	{
		$cids = JRequest :: getVar('cid', array (0), 'post', 'array');
		$row = & $this->getTable('currency');
		$deleteall = 1;
		foreach ($cids as $cid)	{
			if($this->currencyCanDelete($cid) == true){
				if (!$row->delete($cid)){
					$this->setError($row->getErrorMsg());
					return false;
				}
			}else $deleteall++ ;
		}
		return $deleteall;
	}

	function deleteCareerLevel()
	{
		$cids = JRequest :: getVar('cid', array (0), 'post', 'array');
		$row = & $this->getTable('careerlevel');
		$deleteall = 1;
		foreach ($cids as $cid)	{
			if($this->careerLevelCanDelete($cid) == true){
				if (!$row->delete($cid)){
					$this->setError($row->getErrorMsg());
					return false;
				}
			}else $deleteall++ ;
		}
		return $deleteall;
	}
	function deleteExperience()
	{
		$cids = JRequest :: getVar('cid', array (0), 'post', 'array');
		$row = & $this->getTable('experience');
		$deleteall = 1;
		foreach ($cids as $cid)	{
			if($this->experienceCanDelete($cid) == true){
				if (!$row->delete($cid)){
					$this->setError($row->getErrorMsg());
					return false;
				}
			}else $deleteall++ ;
		}
		return $deleteall;
	}

	function deleteJobStatus()
	{
		$cids = JRequest :: getVar('cid', array (0), 'post', 'array');
		$row = & $this->getTable('jobstatus');
		$deleteall = 1;
		foreach ($cids as $cid)	{
			if($this->jobStatusCanDelete($cid) == true){
				if (!$row->delete($cid)){
					$this->setError($row->getErrorMsg());
					return false;
				}
			}else $deleteall++ ;
		}
		return $deleteall;
	}

	function deleteShift()
	{
		$cids = JRequest :: getVar('cid', array (0), 'post', 'array');
		$row = & $this->getTable('shift');
		$deleteall = 1;
		foreach ($cids as $cid)	{
			if($this->shiftCanDelete($cid) == true){
				if (!$row->delete($cid)){
					$this->setError($row->getErrorMsg());
					return false;
				}
			}else $deleteall++ ;
		}
		return $deleteall;
	}

	function deleteHighestEducation()
	{
		$cids = JRequest :: getVar('cid', array (0), 'post', 'array');
		$row = & $this->getTable('highesteducation');
		$deleteall = 1;
		foreach ($cids as $cid)	{
			if($this->highestEducationCanDelete($cid) == true){
				if (!$row->delete($cid)){
					$this->setError($row->getErrorMsg());
					return false;
				}
			}else $deleteall++ ;
		}
		return $deleteall;
	}

	function deleteSalaryRange()
	{
		$cids = JRequest :: getVar('cid', array (0), 'post', 'array');
		$row = & $this->getTable('salaryrange');
		$deleteall = 1;
		foreach ($cids as $cid)	{
			if($this->salaryRangeCanDelete($cid) == true){
				if (!$row->delete($cid)){
					$this->setError($row->getErrorMsg());
					return false;
				}
			}else $deleteall++ ;
		}
		return $deleteall;
	}
	function deleteSalaryRangeType()
	{
		$cids = JRequest :: getVar('cid', array (0), 'post', 'array');
		$row = & $this->getTable('salaryrangetype');
		$deleteall = 1;
		foreach ($cids as $cid)	{
			if($this->salaryRangeTypeCanDelete($cid) == true){
				if (!$row->delete($cid)){
					$this->setError($row->getErrorMsg());
					return false;
				}
			}else $deleteall++ ;
		}
		return $deleteall;
	}

	function deleteRole()
	{
		$cids = JRequest :: getVar('cid', array (0), 'post', 'array');
		$row = & $this->getTable('role');
		$deleteall = 1;
		foreach ($cids as $cid)	{
			if($this->roleCanDelete($cid) == true){
				if (!$row->delete($cid)){
					$this->setError($row->getErrorMsg());
					return false;
				}
			}else $deleteall++ ;
		}
		return $deleteall;
	}

	function deleteUserField()
	{
		$cids = JRequest :: getVar('cid', array (0), 'post', 'array');
		$row = & $this->getTable('userfield');
		$deleteall = 1;
		foreach ($cids as $cid)	{
			if($this->userFieldCanDelete($cid) == true){
				if (!$row->delete($cid)){
					$this->setError($row->getErrorMsg());
					return false;
				}
			}else $deleteall++ ;
		}
		return $deleteall;
	}

	function deleteCountry()
	{
		$cids = JRequest :: getVar('cid', array (0), 'post', 'array');
		$row = & $this->getTable('country');
		$deleteall = 1;
		foreach ($cids as $cid)	{
			if($this->countryCanDelete($cid) == true){
				if (!$row->delete($cid)){
					$this->setError($row->getErrorMsg());
					return false;
				}
			}else $deleteall++ ;
		}
		return $deleteall;
	}
	function deleteState()
	{
		$cids = JRequest :: getVar('cid', array (0), 'post', 'array');
		$row = & $this->getTable('state');
		$deleteall = 1;
		foreach ($cids as $cid)	{
			if($this->stateCanDelete($cid) == true){
				if (!$row->delete($cid)){
					$this->setError($row->getErrorMsg());
					return false;
				}
			}else $deleteall++ ;
		}
		return $deleteall;
	}
	function deleteCounty()
	{
		$cids = JRequest :: getVar('cid', array (0), 'post', 'array');
		$row = & $this->getTable('county');
		$deleteall = 1;
		foreach ($cids as $cid)	{
			if($this->countyCanDelete($cid) == true){
				if (!$row->delete($cid)){
					$this->setError($row->getErrorMsg());
					return false;
				}
			}else $deleteall++ ;
		}
		return $deleteall;
	}
	function deleteCity()
	{
		$cids = JRequest :: getVar('cid', array (0), 'post', 'array');
		$row = & $this->getTable('city');
		$deleteall = 1;
		foreach ($cids as $cid)	{
			if($this->cityCanDelete($cid) == true){
				if (!$row->delete($cid)){
					$this->setError($row->getErrorMsg());
					return false;
				}
			}else $deleteall++ ;
		}
		return $deleteall;
	}

	//##################### CAN DELETE ######################
	function companyCanDelete($companyid){
		if (is_numeric($companyid) == false) return false;
		$db = &$this->getDBO();


		$query = "SELECT
					( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_jobs')." WHERE companyid = ". $companyid .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_departments')." WHERE companyid = ". $companyid .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_featuredcompanies')." WHERE companyid = ". $companyid .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_goldcompanies')." WHERE companyid = ". $companyid .")
					AS total ";
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$total = $db->loadResult();

		if ($total > 0)
			return false;
		else
			return true;
	}

	function companyEnforceDelete($companyid, $uid){
		if (is_numeric($companyid) == false) return false;
		$db = &$this->getDBO();
                $query = "DELETE  company,job,department,featuredcompany,goldcompany
                                 FROM ".$db->nameQuote('#__wrecruit_companies')." AS company
                                 LEFT JOIN ".$db->nameQuote('#__wrecruit_jobs') ." AS job ON company.id=job.companyid
                                 LEFT JOIN ".$db->nameQuote('#__wrecruit_departments') ." AS department ON company.id=department.companyid
                                 LEFT JOIN ".$db->nameQuote('#__wrecruit_featuredcompanies') ." AS featuredcompany ON company.id=featuredcompany.companyid
                                 LEFT JOIN ".$db->nameQuote('#__wrecruit_goldcompanies') ." AS goldcompany ON company.id=goldcompany.companyid
                                 WHERE company.id = ".$companyid;
                //echo '<br> SQL '.$query;
                $db->setQuery($query);
                if (!$db->query()) {
                    return 2; //error while delete company
                }
                return 1;
	}

/* zain */
	function folderEnforceDelete($folderid, $uid){
		if (is_numeric($folderid) == false) return false;
		$db = &$this->getDBO();
                $query = "DELETE  folder
                                 FROM ".$db->nameQuote('#__wrecruit_folders')." AS folder
                                 WHERE folder.id = ".$folderid;
                //echo '<br> SQL '.$query;
                $db->setQuery($query);
                if (!$db->query()) {
                    return 2; //error while delete folder
                }
                return 1;
	}
	function jobCanDelete($jobid){
		if (is_numeric($jobid) == false) return false;
		$db = &$this->getDBO();


		$query = "SELECT
					( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_jobapply')." WHERE jobid = ". $jobid .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_featuredjobs')." WHERE jobid = ". $jobid .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_goldjobs')." WHERE jobid = ". $jobid .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_shortlistcandidates')." WHERE jobid = ". $jobid .")
					AS total ";
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$total = $db->loadResult();

		if ($total > 0)
			return false;
		else
			return true;
	}

	function jobEnforceDelete($jobid, $uid){
		if($uid) if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		if (is_numeric($jobid) == false) return false;
		$db = &$this->getDBO();


                $query = "DELETE  job,apply,featuredjob,goldjob,shortlistcandidate
                                 FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job
                                 LEFT JOIN ".$db->nameQuote('#__wrecruit_jobapply') ." AS apply ON job.id=apply.jobid
                                 LEFT JOIN ".$db->nameQuote('#__wrecruit_featuredjobs') ." AS featuredjob ON job.id=featuredjob.jobid
                                 LEFT JOIN ".$db->nameQuote('#__wrecruit_goldjobs') ." AS goldjob ON job.id=goldjob.jobid
                                 LEFT JOIN ".$db->nameQuote('#__wrecruit_shortlistcandidates') ." AS shortlistcandidate ON job.id=shortlistcandidate.jobid
                                 WHERE job.id = ".$jobid;
                //echo '<br> SQL '.$query;
                $db->setQuery($query);
                if (!$db->query()) {
                    return 2; //error while delete job
                }
		return 1;
	}

	function resumeCanDelete($resumeid){
		if (is_numeric($resumeid) == false) return false;
		$db = &$this->getDBO();


		$query = "SELECT
					( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_jobapply')." WHERE cvid = ". $resumeid .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_featuredresumes')." WHERE resumeid = ". $resumeid .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_goldresumes')." WHERE resumeid = ". $resumeid .")
					AS total ";
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$total = $db->loadResult();

		if ($total > 0)
			return false;
		else
			return true;
	}
	function resumeEnforceDelete($resumeid, $uid){
		if($uid) if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		if (is_numeric($resumeid) == false) return false;
		$db = &$this->getDBO();



                $query = "DELETE  resume,apply,featuredresume,goldresume
                                 FROM ".$db->nameQuote('#__wrecruit_resume')." AS resume
                                 LEFT JOIN ".$db->nameQuote('#__wrecruit_jobapply') ." AS apply ON resume.id=apply.cvid
                                 LEFT JOIN ".$db->nameQuote('#__wrecruit_featuredresumes') ." AS featuredresume ON resume.id=featuredresume.resumeid
                                 LEFT JOIN ".$db->nameQuote('#__wrecruit_goldresumes') ." AS goldresume ON resume.id=goldresume.resumeid
                                 WHERE resume.id = ".$resumeid;
                //echo '<br> SQL '.$query;
                $db->setQuery($query);
                if (!$db->query()) {
                    return 2; //error while delete resume
                }
            return 1;
	}

	function featuredResumeCanDelete($resumeid){
		if (is_numeric($resumeid) == false) return false;
		$db = &$this->getDBO();

		$query = "SELECT COUNT(apply.id) FROM ".$db->nameQuote('#__wrecruit_jobapply')." AS apply
					WHERE apply.cvid = ".$resumeid;
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$total = $db->loadResult();

		if ($total > 0)
			return false;
		else
			return true;
	}
	function categoryCanDelete($categoryid){
		if (is_numeric($categoryid) == false) return false;
		$db = &$this->getDBO();

		$query = "SELECT
					( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_companies')." WHERE category = ". $categoryid .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_jobs')." WHERE jobcategory = ". $categoryid .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE job_category = ". $categoryid .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_subcategories')." WHERE categoryid = ". $categoryid .")
					AS total ";
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$total = $db->loadResult();

		if ($total > 0)
			return false;
		else
			return true;
	}
	function subCategoryCanDelete($categoryid){
		if (is_numeric($categoryid) == false) return false;
		$db = &$this->getDBO();

		$query = "SELECT
					( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_companies')." WHERE category = ". $categoryid .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_jobs')." WHERE jobcategory = ". $categoryid .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE job_category = ". $categoryid .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_subcategories')." WHERE categoryid = ". $categoryid .")
					AS total ";
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$total = $db->loadResult();

		if ($total > 0)
			return false;
		else
			return true;
	}

	function jobTypeCanDelete($typeid){
		if (is_numeric($typeid) == false) return false;
		$db = &$this->getDBO();

		$query = "SELECT
					( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_jobs')." WHERE jobtype = ". $typeid .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE jobtype = ". $typeid .")
					AS total ";
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$total = $db->loadResult();

		if ($total > 0)	return false;
		else return true;
	}

	function ageCanDelete($ageid){
		if (is_numeric($ageid) == false) return false;
		$db = &$this->getDBO();
		$query = " SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_ages')." 
		WHERE id = ". $ageid ." AS total ";
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$total = $db->loadResult();
		if ($total > 0)	return false;
		else return true;
	}
	function currencyCanDelete($currencyid){
		if (is_numeric($currencyid) == false) return false;
		$db = &$this->getDBO();
		$query = " SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_currencies')." 
		WHERE id = ". $currencyid ." AS total ";
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$total = $db->loadResult();
		if ($total > 0)	return false;
		else return true;
	}
	
	function careerLevelCanDelete($careerlevelid){
		if (is_numeric($careerlevelid) == false) return false;
		$db = &$this->getDBO();
		$query = " SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_careerlevels')." 
		WHERE id = ". $careerlevelid ." AS total ";
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$total = $db->loadResult();
		if ($total > 0)	return false;
		else return true;
	}

	function experienceCanDelete($experienceid){
		if (is_numeric($experienceid) == false) return false;
		$db = &$this->getDBO();
		$query = " SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_experiences')."
		WHERE id = ". $experienceid ." AS total ";
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$total = $db->loadResult();
		if ($total > 0)	return false;
		else return true;
	}
	function departmentCanDelete($departmentid){
		if (is_numeric($departmentid) == false) return false;
		$db = &$this->getDBO();

		$query = "SELECT
					( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_jobs')." WHERE departmentid = ". $departmentid .")
					AS total ";
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$total = $db->loadResult();

		if ($total > 0)	return false;
		else return true;
	}

	function jobStatusCanDelete($statusid){
		if (is_numeric($statusid) == false) return false;
		$db = &$this->getDBO();

		$query = "SELECT
					( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_jobs')." WHERE jobstatus = ". $statusid .")
					AS total ";
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$total = $db->loadResult();

		if ($total > 0)	return false;
		else return true;
	}

	function shiftCanDelete($shiftid){
		if (is_numeric($shiftid) == false) return false;
		$db = &$this->getDBO();

		$query = "SELECT
					( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_jobs')." WHERE shift = ". $shiftid .")
					AS total ";
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$total = $db->loadResult();

		if ($total > 0)	return false;
		else return true;
	}

	function highestEducationCanDelete($educationid){
		if (is_numeric($educationid) == false) return false;
		$db = &$this->getDBO();

		$query = "SELECT
					( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_jobs')." WHERE heighestfinisheducation = ". $educationid .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE heighestfinisheducation = ". $educationid .")
					AS total ";
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$total = $db->loadResult();

		if ($total > 0)	return false;
		else return true;
	}

	function salaryRangeCanDelete($salaryid){
		if (is_numeric($salaryid) == false) return false;
		$db = &$this->getDBO();

		$query = "SELECT
					( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_jobs')." WHERE jobsalaryrange = ". $salaryid .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE jobsalaryrange = ". $salaryid .")
					AS total ";
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$total = $db->loadResult();

		if ($total > 0)
			return false;
		else
			return true;
	}

	function salaryRangeTypeCanDelete($id){
		if (is_numeric($id) == false) return false;
		$db = &$this->getDBO();
		$query = " SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_salaryrangetypes')." 
		WHERE id = ". $id .") AS total ";
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$total = $db->loadResult();
		if ($total > 0)	return false;
		else return true;
	}
	function roleCanDelete($roleid){
		$db = &$this->getDBO();

		$query = "SELECT COUNT(userrole.id) FROM ".$db->nameQuote('#__wrecruit_userroles')." AS userrole
					WHERE userrole.role = ".$roleid;
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$total = $db->loadResult();

		if ($total > 0)
			return false;
		else
			return true;
	}

	function userFieldCanDelete($field){
		$db = &$this->getDBO();

		$query = "SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_userfieldvalues')." WHERE field = ". $country->field."	AS total ";
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$total = $db->loadResult();

		if ($total > 0)
			return false;
		else
			return true;
	}

	function countryCanDelete($countryid){
		if (is_numeric($countryid) == false) return false;
		$db = &$this->getDBO();

		$query = "SELECT code FROM ".$db->nameQuote('#__wrecruit_countries')."	WHERE id = ".$countryid;
		$db->setQuery($query);
		$country = $db->loadObject();

		$query = "SELECT
					( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_jobs')." WHERE country = ". $db->Quote($country->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_companies')." WHERE country = ". $db->Quote($country->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE nationality = ". $db->Quote($country->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE address_country = ". $db->Quote($country->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE address1_country = ". $db->Quote($country->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE address2_country = ". $db->Quote($country->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE institute_country = ". $db->Quote($country->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE institute1_country = ". $db->Quote($country->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE institute2_country = ". $db->Quote($country->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE institute3_country = ". $db->Quote($country->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE employer_country = ". $db->Quote($country->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE employer1_country = ". $db->Quote($country->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE employer2_country = ". $db->Quote($country->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE employer3_country = ". $db->Quote($country->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE reference_country = ". $db->Quote($country->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE reference1_country = ". $db->Quote($country->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE reference2_country = ". $db->Quote($country->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE reference3_country = ". $db->Quote($country->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_states')." WHERE countrycode = ". $db->Quote($country->code) .")
					AS total ";
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$total = $db->loadResult();

		if ($total > 0)
			return false;
		else
			return true;
	}
	function stateCanDelete($stateid){
		if (is_numeric($stateid) == false) return false;
		$db = &$this->getDBO();

		$query = "SELECT code FROM ".$db->nameQuote('#__wrecruit_states')."	WHERE id = ".$stateid;
		$db->setQuery($query);
		$state = $db->loadObject();

		$query = "SELECT
					( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_jobs')." WHERE state = ". $db->Quote($state->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_companies')." WHERE state = ". $db->Quote($state->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE address_state = ". $db->Quote($state->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE address1_state = ". $db->Quote($state->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE address2_state = ". $db->Quote($state->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE institute_state = ". $db->Quote($state->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE institute1_state = ". $db->Quote($state->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE institute2_state = ". $db->Quote($state->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE institute3_state = ". $db->Quote($state->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE employer_state = ". $db->Quote($state->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE employer1_state = ". $db->Quote($state->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE employer2_state = ". $db->Quote($state->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE employer3_state = ". $db->Quote($state->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE reference_state = ". $db->Quote($state->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE reference1_state = ". $db->Quote($state->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE reference2_state = ". $db->Quote($state->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE reference3_state = ". $db->Quote($state->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_counties')." WHERE statecode = ". $db->Quote($state->code) .")
					AS total ";
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$total = $db->loadResult();

		if ($total > 0)
			return false;
		else
			return true;
	}
	function countyCanDelete($countyid){
		if (is_numeric($countyid) == false) return false;
		$db = &$this->getDBO();

		$query = "SELECT code FROM ".$db->nameQuote('#__wrecruit_counties')."	WHERE id = ".$countyid;
		$db->setQuery($query);
		$county = $db->loadObject();

		$query = "SELECT
					( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_jobs')." WHERE county = ". $db->Quote($county->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_companies')." WHERE county = ". $db->Quote($county->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE address_county = ". $db->Quote($county->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE address1_county = ". $db->Quote($county->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE address2_county = ". $db->Quote($county->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE institute_county = ". $db->Quote($county->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE institute1_county = ". $db->Quote($county->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE institute2_county = ". $db->Quote($county->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE institute3_county = ". $db->Quote($county->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE employer_county = ". $db->Quote($county->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE employer1_county = ". $db->Quote($county->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE employer2_county = ". $db->Quote($county->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE employer3_county = ". $db->Quote($county->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE reference_county = ". $db->Quote($county->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE reference1_county = ". $db->Quote($county->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE reference2_county = ". $db->Quote($county->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE reference3_county = ". $db->Quote($county->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_cities')." WHERE countycode = ". $db->Quote($county->code) .")
					AS total ";
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$total = $db->loadResult();

		if ($total > 0)
			return false;
		else
			return true;
	}
	function cityCanDelete($cityid){
		if (is_numeric($cityid) == false) return false;
		$db = &$this->getDBO();

		$query = "SELECT code FROM ".$db->nameQuote('#__wrecruit_cities')."	WHERE id = ".$cityid;
		$db->setQuery($query);
		$city = $db->loadObject();

		$query = "SELECT
					( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_jobs')." WHERE city = ". $db->Quote($city->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_companies')." WHERE city = ". $db->Quote($city->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE address_city = ". $db->Quote($city->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE address1_city = ". $db->Quote($city->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE address2_city = ". $db->Quote($city->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE institute_city = ". $db->Quote($city->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE institute1_city = ". $db->Quote($city->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE institute2_city = ". $db->Quote($city->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE institute3_city = ". $db->Quote($city->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE employer_city = ". $db->Quote($city->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE employer1_city = ". $db->Quote($city->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE employer2_city = ". $db->Quote($city->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE employer3_city = ". $db->Quote($city->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE reference_city = ". $db->Quote($city->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE reference1_city = ". $db->Quote($city->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE reference2_city = ". $db->Quote($city->code) .")
					+ ( SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_resume')." WHERE reference3_city = ". $db->Quote($city->code) .")
					AS total ";
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$total = $db->loadResult();

		if ($total > 0)
			return false;
		else
			return true;
	}
        function deleteJobSeekerPackage()
	{
		$cids = JRequest :: getVar('cid', array (0), 'post', 'array');
		$row = & $this->getTable('jobseekerpackage');
		$deleteall = 1;
		foreach ($cids as $cid)	{
			if($this->jobseekerPackageCanDelete($cid) == true){

				if (!$row->delete($cid)){
					$this->setError($row->getErrorMsg());
					return false;
				}
			}else $deleteall++ ;
		}
		return $deleteall;
	}

	function jobseekerPackageCanDelete($id){
		if (is_numeric($id) == false) return false;
		$db = &$this->getDBO();

		$query = "SELECT COUNT(id) FROM ".$db->nameQuote('#__wrecruit_jobseekerpaymenthistory')." WHERE packageid = ". $id ."

					AS total ";
		//echo '<br> SQL '.$query;
		$db->setQuery($query);
		$total = $db->loadResult();

		if ($total > 0)
			return false;
		else
			return true;
	}


// Delete Code End

// Payment System start
	function & getGoldResumes($searchtitle,$searchname,$searchjobseekerpackage,$limitstart, $limit)
	{
		$db = & JFactory :: getDBO();
		$result = array();
		$query = "SELECT COUNT(goldresumes.id)
		FROM #__wrecruit_goldresumes AS goldresumes
		JOIN #__wrecruit_jobseekerpackages AS package ON package.id=goldresumes.packageid
		WHERE goldresumes.status <> 0";

		if ($searchtitle) $query .= " AND LOWER(app.application_title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchtitle, true ).'%', false );
		if ($searchname) {
			$query .= " AND (";
				$query .= " LOWER(app.first_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
				$query .= " OR LOWER(app.last_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
				$query .= " OR LOWER(app.middle_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
			$query .= " )";
		}
		if ($searchjobseekerpackage) $query .= " AND LOWER(package.title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchjobseekerpackage, true ).'%', false );

		$db->setQuery($query);
		$total = $db->loadResult();
                if ( $total <= $limitstart ) $limitstart = 0;


		$query = "SELECT goldresumes.*,app.application_title,app.first_name, app.last_name,
				app.create_date, package.title AS packagetitle
				FROM #__wrecruit_goldresumes AS goldresumes ,#__wrecruit_resume AS app, #__wrecruit_jobseekerpackages AS package
				WHERE app.id=goldresumes.resumeid AND  package.id=goldresumes.packageid AND goldresumes.status <> 0";


		if ($searchtitle) $query .= " AND LOWER(app.application_title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchtitle, true ).'%', false );
		if ($searchname) {
			$query .= " AND (";
				$query .= " LOWER(app.first_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
				$query .= " OR LOWER(app.last_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
				$query .= " OR LOWER(app.middle_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
			$query .= " )";
		}

		if ($searchjobseekerpackage) $query .= " AND LOWER(package.title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchjobseekerpackage, true ).'%', false );

		$query .= " ORDER BY app.create_date DESC";
		//echo $query;

		$db->setQuery($query,$limitstart, $limit);
		$goldresumes = $db->loadObjectList();

			$lists = array();



			if ($searchtitle) $lists['searchtitle'] = $searchtitle;
			if ($searchname) $lists['searchname'] = $searchname;
			if ($searchjobseekerpackage) $lists['searchjobseekerpackage'] = $searchjobseekerpackage;


		$result[0] = $goldresumes;
		$result[1] = $total;
		$result[2] = $lists;
		return $result;

	}
	function & getAllUnapprovedGoldResume($searchtitle,$searchname,$searchjobseekerpackage,$limitstart, $limit)
	{
		$db = & JFactory :: getDBO();
		$result = array();
		$query = "SELECT COUNT(goldresumes.id)
		FROM #__wrecruit_goldresumes AS goldresumes
		JOIN #__wrecruit_jobseekerpackages AS package ON package.id=goldresumes.packageid
		WHERE goldresumes.status = 0";

		if ($searchtitle) $query .= " AND LOWER(app.application_title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchtitle, true ).'%', false );
		if ($searchname) {
			$query .= " AND (";
				$query .= " LOWER(app.first_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
				$query .= " OR LOWER(app.last_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
				$query .= " OR LOWER(app.middle_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
			$query .= " )";
		}
		if ($searchjobseekerpackage) $query .= " AND LOWER(package.title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchjobseekerpackage, true ).'%', false );

		$db->setQuery($query);
		$total = $db->loadResult();
                if ( $total <= $limitstart ) $limitstart = 0;


		$query = "SELECT goldresumes.*,app.application_title,app.first_name, app.last_name,
				app.create_date, package.title AS packagetitle
				FROM #__wrecruit_goldresumes AS goldresumes ,#__wrecruit_resume AS app, #__wrecruit_jobseekerpackages AS package
				WHERE app.id=goldresumes.resumeid AND  package.id=goldresumes.packageid AND goldresumes.status = 0";


		if ($searchtitle) $query .= " AND LOWER(app.application_title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchtitle, true ).'%', false );
		if ($searchname) {
			$query .= " AND (";
				$query .= " LOWER(app.first_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
				$query .= " OR LOWER(app.last_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
				$query .= " OR LOWER(app.middle_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
			$query .= " )";
		}

		if ($searchjobseekerpackage) $query .= " AND LOWER(package.title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchjobseekerpackage, true ).'%', false );

		$query .= " ORDER BY app.create_date DESC";
		//echo $query;

		$db->setQuery($query,$limitstart, $limit);
		$goldresumes = $db->loadObjectList();

			$lists = array();



			if ($searchtitle) $lists['searchtitle'] = $searchtitle;
			if ($searchname) $lists['searchname'] = $searchname;
			if ($searchjobseekerpackage) $lists['searchjobseekerpackage'] = $searchjobseekerpackage;


		$result[0] = $goldresumes;
		$result[1] = $total;
		$result[2] = $lists;
		return $result;

	}
	function & getGoldResumeById($resumeid,$c_id)
	{
		$db = & JFactory :: getDBO();
		if (is_numeric($resumeid) == false) return false;
		if (is_numeric($c_id) == false) return false;
		$result = array();
		
		$query = "SELECT goldresume.*,resume.application_title
		FROM #__wrecruit_goldresumes AS goldresume 
		JOIN #__wrecruit_resume AS resume ON resume.id=goldresume.resumeid
		WHERE goldresume.id=".$c_id;
		//echo $query;
		$db->setQuery($query);
		$goldresume = $db->loadObject();

		if ( isset($goldresume) ){
			$lists['jobseekerpackage'] = JHTML::_('select.genericList', $this->getJobSeekerPackageForCombo(''), 'packageid', 'class="inputbox required" '. '', 'value', 'text', $goldresume->packageid);

		}else{
			$lists['jobseekerpackage'] = JHTML::_('select.genericList', $this->getJobSeekerPackageForCombo(''), 'packageid', 'class="inputbox required" '. '', 'value', 'text', '');
	}


		$query = "SELECT resume.application_title
		FROM #__wrecruit_resume AS resume 
		WHERE resume.id=".$resumeid;
		//echo $query;
		$db->setQuery($query);
		$application_title = $db->loadResult();

		$result[0] = $goldresume;
		$result[1] = $lists;
		$result[2] = $application_title;
		return $result;
	}
	function storeGoldResume($uid, $resumeid)
	{
		if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		if (is_numeric($resumeid) == false) return false;
		$row = & $this->getTable('goldresume');

		$data = JRequest :: get('post');
		$row->created=date('Y-m-d H:i:s');
		$data['startdate'] =  date('Y-m-d H:i:s',strtotime($data['startdate']));	
		$data['enddate'] =  date('Y-m-d H:i:s',strtotime($data['enddate']));	
		
		if (!$row->bind($data))	{
			$this->setError($this->_db->getErrorMsg());
			echo $this->_db->getErrorMsg();
			return false;
		}
		if ($data['id'] == ''){ // only for new
			$result=$this->GoldResumeValidation($uid, $resumeid);
			if ($result == false)
			{
				return 6;
			}
		}
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			echo $this->_db->getErrorMsg();
			return false;
		}
		return true;
	}
	function GoldResumeValidation($uid, $resumeid)
	{
		
		$db =& JFactory::getDBO();
		if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		
		$query = "SELECT COUNT(goldresume.id)  
		FROM #__wrecruit_goldresumes  AS goldresume
		JOIN #__wrecruit_jobseekerpackages AS package ON package.id=goldresume.packageid
		WHERE goldresume.uid = ".$uid ." AND goldresume.resumeid = ".$resumeid." 
		AND DATE_ADD(goldresume.created,INTERVAL package.goldresumeexpireindays DAY) >= CURDATE()";
	
		//echo '<br>sql '.$query;
		$db->setQuery( $query );
		$result = $db->loadResult();
		//echo '<br>r'.$result;
		if ($result == 0)
			return true;
		else
			return false;
			
	}
	
	function deleteGoldResume()
	{
		$cids = JRequest :: getVar('cid', array (0), 'post', 'array');
		$row = & $this->getTable('goldresume');
		$deleteall = 1;
		foreach ($cids as $cid)	{
                    if (!$row->delete($cid)){
                            $this->setError($row->getErrorMsg());
                            return false;
                    }
		}
		return true;
	}
	
	function &getFeaturedResumes($searchtitle,$searchname,$searchemployerpackage,$limitstart, $limit)
	{

		$db = & JFactory :: getDBO();
		$result = array();
		$query = "SELECT COUNT(featuredresumes.id) 
		FROM #__wrecruit_featuredresumes AS featuredresumes
		JOIN #__wrecruit_jobseekerpackages AS package ON package.id=featuredresumes.packageid
		WHERE featuredresumes.status <> 0";
		if ($searchtitle) $query .= " AND LOWER(app.application_title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchtitle, true ).'%', false );
		if ($searchname) {
			$query .= " AND (";
				$query .= " LOWER(app.first_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
				$query .= " OR LOWER(app.last_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
				$query .= " OR LOWER(app.middle_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
			$query .= " )";
		}	
		if ($searchemployerpackage) $query .= " AND LOWER(package.title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchemployerpackage, true ).'%', false );

		$db->setQuery($query);
		$total = $db->loadResult();
                if ( $total <= $limitstart ) $limitstart = 0;

		$query = "SELECT featuredresumes.*,app.application_title,app.first_name, app.last_name 
				, app.create_date,package.title AS packagetitle
				FROM #__wrecruit_featuredresumes AS featuredresumes ,#__wrecruit_resume AS app,#__wrecruit_jobseekerpackages AS package
				WHERE app.id=featuredresumes.resumeid AND  package.id=featuredresumes.packageid AND featuredresumes.status <> 0";
		
		
		if ($searchtitle) $query .= " AND LOWER(app.application_title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchtitle, true ).'%', false );
		if ($searchname) {
			$query .= " AND (";
				$query .= " LOWER(app.first_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
				$query .= " OR LOWER(app.last_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
				$query .= " OR LOWER(app.middle_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
			$query .= " )";
		}	
		if ($searchemployerpackage) $query .= " AND LOWER(package.title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchemployerpackage, true ).'%', false );

		
		$query .= " ORDER BY app.create_date DESC";
		//echo $query;
		$db->setQuery($query,$limitstart, $limit);
		$featuredresumes = $db->loadObjectList();

			$lists = array();
			
			
			
			if ($searchtitle) $lists['searchtitle'] = $searchtitle;
			if ($searchname) $lists['searchname'] = $searchname;
			if ($searchemployerpackage) $lists['searchemployerpackage'] = $searchemployerpackage;

		

		$result[0] = $featuredresumes;
		$result[1] = $total;
		$result[2] = $lists;
		return $result;
	}
	
	
	function & getAllUnapprovedFeaturedResume($searchtitle,$searchname,$searchjobseekerpackage,$limitstart, $limit)
	{
		
		
		$db = & JFactory :: getDBO();
		$result = array();
		$query = "SELECT COUNT(featuredresumes.id) 
		FROM #__wrecruit_featuredresumes AS featuredresumes
		JOIN #__wrecruit_jobseekerpackages AS package ON package.id=featuredresumes.packageid
		WHERE featuredresumes.status = 0";
		if ($searchtitle) $query .= " AND LOWER(app.application_title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchtitle, true ).'%', false );
		if ($searchname) {
			$query .= " AND (";
				$query .= " LOWER(app.first_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
				$query .= " OR LOWER(app.last_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
				$query .= " OR LOWER(app.middle_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
			$query .= " )";
		}	
		if ($searchjobseekerpackage) $query .= " AND LOWER(package.title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchjobseekerpackage, true ).'%', false );

		$db->setQuery($query);
		$total = $db->loadResult();
                if ( $total <= $limitstart ) $limitstart = 0;

		$query = "SELECT featuredresumes.*,app.application_title,app.first_name, app.last_name 
				, app.create_date,package.title AS packagetitle
				FROM #__wrecruit_featuredresumes AS featuredresumes ,#__wrecruit_resume AS app,#__wrecruit_jobseekerpackages AS package
				WHERE app.id=featuredresumes.resumeid AND  package.id=featuredresumes.packageid AND featuredresumes.status = 0";
		
		
		if ($searchtitle) $query .= " AND LOWER(app.application_title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchtitle, true ).'%', false );
		if ($searchname) {
			$query .= " AND (";
				$query .= " LOWER(app.first_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
				$query .= " OR LOWER(app.last_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
				$query .= " OR LOWER(app.middle_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchname, true ).'%', false );
			$query .= " )";
		}	
		if ($searchjobseekerpackage) $query .= " AND LOWER(package.title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchjobseekerpackage, true ).'%', false );

		
		$query .= " ORDER BY app.create_date DESC";
		//echo $query;
		$db->setQuery($query,$limitstart, $limit);
		$featuredresumes = $db->loadObjectList();

			$lists = array();
			
			
			
			if ($searchtitle) $lists['searchtitle'] = $searchtitle;

			if ($searchname) $lists['searchname'] = $searchname;
			if ($searchjobseekerpackage) $lists['searchjobseekerpackage'] = $searchjobseekerpackage;

		

		$result[0] = $featuredresumes;
		$result[1] = $total;
		$result[2] = $lists;
		return  $result;
	}
	
	
	function & getFeaturedResumeById($resumeid,$c_id)
	{
		if (is_numeric($resumeid) == false) return false;
		if (is_numeric($c_id) == false) return false;
		$db = & JFactory :: getDBO();
		$result = array();
		
		$query = "SELECT featuredresume.*,resume.application_title
		FROM #__wrecruit_featuredresumes AS featuredresume 
		JOIN #__wrecruit_resume AS resume ON resume.id=featuredresume.resumeid
		WHERE featuredresume.id=".$c_id;
		//echo $query;
		$db->setQuery($query);
		$featuredresume = $db->loadObject();
		if ( isset($featuredresume) ){
			$lists['jobseekerpackage'] = JHTML::_('select.genericList', $this->getJobSeekerPackageForCombo(''), 'packageid', 'class="inputbox required" '. '', 'value', 'text', $featuredresume->packageid);

		}else{
			$lists['jobseekerpackage'] = JHTML::_('select.genericList', $this->getJobSeekerPackageForCombo(''), 'packageid', 'class="inputbox required" '. '', 'value', 'text', '');
                }
	
		$query = "SELECT resume.application_title
		FROM #__wrecruit_resume AS resume 
		WHERE resume.id=".$resumeid;
		//echo $query;
		$db->setQuery($query);
		$application_title = $db->loadResult();
	

		$result[0] = $featuredresume;
		$result[1] = $lists;
		$result[2] = $application_title;
		return $result;
	}
	
	function storeFeaturedResume($uid, $resumeid)
	{
		if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		if (is_numeric($resumeid) == false) return false;
		$row = & $this->getTable('featuredresume');

		$data = JRequest :: get('post');
		$data['startdate'] =  date('Y-m-d H:i:s',strtotime($data['startdate']));	
		$data['enddate'] =  date('Y-m-d H:i:s',strtotime($data['enddate']));	
		 $row->created = date('Y-m-d H:i:s');
		if (!$row->bind($data))	{
			$this->setError($this->_db->getErrorMsg());
			echo $this->_db->getErrorMsg();
			return false;
		}
		if ($data['id'] == ''){ // only for new
			$result=$this->featuredResumeValidation($uid, $resumeid);
			
			if ($result == false) return 6;
		}
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			echo $this->_db->getErrorMsg();
			return false;
		}
		return true;
	}

	function featuredResumeValidation($uid, $resumeid)
	{
		$db =& JFactory::getDBO();
		if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		
		$query = "SELECT COUNT(featuredresume.id)  
		FROM #__wrecruit_featuredresumes  AS featuredresume
		JOIN #__wrecruit_jobseekerpackages AS package ON package.id=featuredresume.packageid
		WHERE featuredresume.uid = ".$uid ." AND featuredresume.resumeid = ".$resumeid." 
		AND DATE_ADD(featuredresume.created,INTERVAL package.freaturedresumeexpireindays DAY) >= CURDATE()";
		$db->setQuery( $query );
		$result = $db->loadResult();
		if ($result == 0) return true;
		else return false;
	}
	
	function deleteFeaturedResume()
	{
		$cids = JRequest :: getVar('cid', array (0), 'post', 'array');
		$row = & $this->getTable('featuredresume');
		$deleteall = 1;
		foreach ($cids as $cid)	{
                    if (!$row->delete($cid)){
                            $this->setError($row->getErrorMsg());
                            return false;
                    }
		}
		return true;
	
	}
	function & getGoldJobs($searchtitle,$searchcompany,$searchemployerpackage,$limitstart, $limit)
	{

		$db = & JFactory :: getDBO();
		$result = array();
		$query = "SELECT COUNT(goldjobs.id)
		FROM #__wrecruit_goldjobs AS goldjobs
		JOIN   #__wrecruit_jobs AS jobs  ON  jobs.id=goldjobs.jobid
		LEFT JOIN #__wrecruit_employerpackages AS package ON package.id=goldjobs.packageid
		LEFT JOIN #__wrecruit_companies AS company ON  company.id=jobs.companyid
		WHERE goldjobs.status <> 0";


		if ($searchtitle) $query .= " AND LOWER(jobs.title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchtitle, true ).'%', false );
		if ($searchcompany) $query .= " AND LOWER(company.name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchcompany, true ).'%', false );
		if ($searchemployerpackage) $query .= " AND LOWER(package.title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchemployerpackage, true ).'%', false );


		$db->setQuery($query);
		$total = $db->loadResult();
                if ( $total <= $limitstart ) $limitstart = 0;

		$query = "SELECT goldjobs.*,jobs.title,company.name AS companyname,package.title AS packagetitle,package.status AS packagestatus,
		package.created AS packagecreated
		FROM #__wrecruit_goldjobs AS goldjobs
		JOIN   #__wrecruit_jobs AS jobs  ON  jobs.id=goldjobs.jobid
		LEFT JOIN #__wrecruit_employerpackages AS package ON package.id=goldjobs.packageid
		LEFT JOIN #__wrecruit_companies AS company ON  company.id=jobs.companyid
		WHERE goldjobs.status <> 0";

		if ($searchtitle) $query .= " AND LOWER(jobs.title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchtitle, true ).'%', false );
		if ($searchcompany) $query .= " AND LOWER(company.name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchcompany, true ).'%', false );
		if ($searchemployerpackage) $query .= " AND LOWER(package.title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchemployerpackage, true ).'%', false );

		$query .= " ORDER BY jobs.created DESC";

		//echo $query;
			$db->setQuery($query,$limitstart, $limit);
		$goldjobs = $db->loadObjectList();

			$lists = array();


			if ($searchtitle) $lists['searchtitle'] = $searchtitle;
			if ($searchcompany) $lists['searchcompany'] = $searchcompany;
			if ($searchemployerpackage) $lists['searchemployerpackage'] = $searchemployerpackage;


		$result[0] = $goldjobs;
		$result[1] = $total;
		$result[2] = $lists;
		return $result;

	 	}


	function & getAllUnapprovedGoldJobs($searchtitle,$searchcompany,$searchemployerpackage,$limitstart, $limit)
	{

		$db = & JFactory :: getDBO();
		$result = array();
		$query = "SELECT COUNT(goldjobs.id)
		FROM #__wrecruit_goldjobs AS goldjobs
		JOIN   #__wrecruit_jobs AS jobs  ON  jobs.id=goldjobs.jobid
		LEFT JOIN #__wrecruit_employerpackages AS package ON package.id=goldjobs.packageid
		LEFT JOIN #__wrecruit_companies AS company ON  company.id=jobs.companyid
		WHERE goldjobs.status = 0";


		if ($searchtitle) $query .= " AND LOWER(jobs.title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchtitle, true ).'%', false );
		if ($searchcompany) $query .= " AND LOWER(company.name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchcompany, true ).'%', false );
		if ($searchemployerpackage) $query .= " AND LOWER(package.title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchemployerpackage, true ).'%', false );


		$db->setQuery($query);
		$total = $db->loadResult();
                if ( $total <= $limitstart ) $limitstart = 0;

		$query = "SELECT goldjobs.*,jobs.title,company.name AS companyname,package.title AS packagetitle,package.status AS packagestatus,
		package.created AS packagecreated
		FROM #__wrecruit_goldjobs AS goldjobs
		JOIN   #__wrecruit_jobs AS jobs  ON  jobs.id=goldjobs.jobid
		LEFT JOIN #__wrecruit_employerpackages AS package ON package.id=goldjobs.packageid
		LEFT JOIN #__wrecruit_companies AS company ON  company.id=jobs.companyid
		WHERE goldjobs.status = 0";

		if ($searchtitle) $query .= " AND LOWER(jobs.title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchtitle, true ).'%', false );
		if ($searchcompany) $query .= " AND LOWER(company.name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchcompany, true ).'%', false );
		if ($searchemployerpackage) $query .= " AND LOWER(package.title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchemployerpackage, true ).'%', false );

		$query .= " ORDER BY jobs.created DESC";

		//echo $query;
			$db->setQuery($query,$limitstart, $limit);
		$goldjobs = $db->loadObjectList();
			$lists = array();


			if ($searchtitle) $lists['searchtitle'] = $searchtitle;
			if ($searchcompany) $lists['searchcompany'] = $searchcompany;
			if ($searchemployerpackage) $lists['searchemployerpackage'] = $searchemployerpackage;



		$result[0] = $goldjobs;
		$result[1] = $total;
		$result[2] = $lists;
		return $result;

	}


	function & getGoldJobId($jobid,$c_id)
	{
		if (is_numeric($jobid) == false) return false;
		if (is_numeric($c_id) == false) return false;

		$db = & JFactory :: getDBO();
		$result = array();

		$query = "SELECT goldjob.*,job.title AS jobtitle
		FROM #__wrecruit_goldjobs AS goldjob
		JOIN #__wrecruit_jobs AS job ON job.id=goldjob.jobid
		 WHERE goldjob.id=".$c_id;
		//echo $query;
		$db->setQuery($query);
		$goldjob = $db->loadObject();

		if ( isset($goldjob) ){
			$lists['employerpackage'] = JHTML::_('select.genericList', $this->getEmployerPackageForCombo(''), 'packageid', 'class="inputbox required" '. '', 'value', 'text', $goldjob->packageid);

		}else{
			$lists['employerpackage'] = JHTML::_('select.genericList', $this->getEmployerPackageForCombo(''), 'packageid', 'class="inputbox required" '. '', 'value', 'text', '');
                }


		$query = "SELECT job.title AS jobtitle
		 FROM #__wrecruit_jobs AS job
		 WHERE job.id=".$jobid;

		$db->setQuery($query);
		$jobtitle = $db->loadResult();

		$result[0] = $goldjob;
		$result[1] = $lists;
		$result[2] = $jobtitle;
		return $result;

	}



	function storeGoldJob($jobid,$uid)
	{
		if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		if (is_numeric($jobid) == false) return false;
		$row = & $this->getTable('goldjob');
		$data = JRequest :: get('post');
		$row->created = date('Y-m-d H:i:s');

		if (!$row->bind($data))	{
			$this->setError($this->_db->getErrorMsg());
			echo $this->_db->getErrorMsg();
			return false;
		}

		if ($data['id'] == ''){ // only for new
			$result=$this->goldJobValidation($uid, $jobid);
			if ($result == false)
			{
				return 6;
			}
		}

		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			echo $this->_db->getErrorMsg();
			return false;
		}
		return true;
	}

	function goldJobValidation($uid, $jobid)
	{

		$db =& JFactory::getDBO();
		if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;

		$query = "SELECT COUNT(goldjob.id)
		FROM #__wrecruit_goldjobs  AS goldjob
		JOIN #__wrecruit_employerpackages AS package ON package.id=goldjob.packageid
		WHERE goldjob.uid = ".$uid ." AND goldjob.jobid = ".$jobid."
		AND DATE_ADD(goldjob.created,INTERVAL package.goldjobsexpireindays DAY) >= CURDATE()";

		//echo '<br>sql '.$query;
		$db->setQuery( $query );
		$result = $db->loadResult();
		//echo '<br>r'.$result;
		if ($result == 0)
			return true;
		else
			return false;

	}

	function deleteGoldJob()
	{
		$cids = JRequest :: getVar('cid', array (0), 'post', 'array');
		$row = & $this->getTable('goldjob');
		$deleteall = 1;
		foreach ($cids as $cid)	{

				if (!$row->delete($cid)){
					$this->setError($row->getErrorMsg());
					return false;
				}

		}
		return true;

	}
	function & getFeaturedJobs($searchtitle,$searchcompany,$searchemployerpackage,$limitstart, $limit)
	{
		$db = & JFactory :: getDBO();
		$result = array();
		$query = "SELECT COUNT(featuredjobs.id)
		FROM #__wrecruit_featuredjobs AS featuredjobs
		JOIN   #__wrecruit_jobs AS jobs  ON  jobs.id=featuredjobs.jobid
		LEFT JOIN #__wrecruit_employerpackages AS package ON package.id=featuredjobs.packageid
		LEFT JOIN #__wrecruit_companies AS company ON  company.id=jobs.companyid
		WHERE featuredjobs.status <> 0";


		if ($searchtitle) $query .= " AND LOWER(jobs.title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchtitle, true ).'%', false );
		if ($searchcompany) $query .= " AND LOWER(company.name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchcompany, true ).'%', false );
		if ($searchemployerpackage) $query .= " AND LOWER(package.title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchemployerpackage, true ).'%', false );


		$db->setQuery($query);
		$total = $db->loadResult();
                if ( $total <= $limitstart ) $limitstart = 0;

		$query = "SELECT featuredjobs.*,jobs.title,company.name AS companyname,package.title AS packagetitle,package.status AS packagestatus,
		package.created AS packagecreated
		FROM #__wrecruit_featuredjobs AS featuredjobs
		JOIN   #__wrecruit_jobs AS jobs  ON  jobs.id=featuredjobs.jobid
		LEFT JOIN #__wrecruit_employerpackages AS package ON package.id=featuredjobs.packageid
		LEFT JOIN #__wrecruit_companies AS company ON  company.id=jobs.companyid
		WHERE featuredjobs.status <> 0";

		if ($searchtitle) $query .= " AND LOWER(jobs.title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchtitle, true ).'%', false );
		if ($searchcompany) $query .= " AND LOWER(company.name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchcompany, true ).'%', false );
		if ($searchemployerpackage) $query .= " AND LOWER(package.title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchemployerpackage, true ).'%', false );

		$query .= " ORDER BY jobs.created DESC";

		//echo $query;
                $db->setQuery($query,$limitstart, $limit);
                $featuredjobs = $db->loadObjectList();
                $lists = array();

                $job_type = $this->getJobType(JText::_('JS_SELECT_JOB_TYPE'));
                $jobstatus = $this->getJobStatus(JText::_('JS_SELECT_JOB_STATUS'));

                $job_categories = $this->getCategories(JText::_('JS_SELECT_JOB_CATEGORY'),'');
                if ($searchtitle) $lists['searchtitle'] = $searchtitle;
                if ($searchcompany) $lists['searchcompany'] = $searchcompany;
                if ($searchemployerpackage) $lists['searchemployerpackage'] = $searchemployerpackage;

		$db->setQuery($query,$limitstart, $limit);
		$featuredjobs = $db->loadObjectList();

		$result[0] = $featuredjobs;
		$result[1] = $total;
		$result[2] = $lists;
		return $result;
	}

        function & getAllUnapprovedFeaturedJobs($searchtitle,$searchcompany,$searchemployerpackage,$limitstart, $limit)
	{
		$db = & JFactory :: getDBO();
		$result = array();
		$query = "SELECT COUNT(featuredjobs.id)
		FROM #__wrecruit_featuredjobs AS featuredjobs
		JOIN   #__wrecruit_jobs AS jobs  ON  jobs.id=featuredjobs.jobid
		LEFT JOIN #__wrecruit_employerpackages AS package ON package.id=featuredjobs.packageid
		LEFT JOIN #__wrecruit_companies AS company ON  company.id=jobs.companyid
		WHERE featuredjobs.status = 0";


		if ($searchtitle) $query .= " AND LOWER(jobs.title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchtitle, true ).'%', false );
		if ($searchcompany) $query .= " AND LOWER(company.name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchcompany, true ).'%', false );
		if ($searchemployerpackage) $query .= " AND LOWER(package.title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchemployerpackage, true ).'%', false );


		$db->setQuery($query);
		$total = $db->loadResult();
                if ( $total <= $limitstart ) $limitstart = 0;

		$query = "SELECT featuredjobs.*,jobs.title,company.name AS companyname,package.title AS packagetitle,package.status AS packagestatus,
		package.created AS packagecreated
		FROM #__wrecruit_featuredjobs AS featuredjobs
		JOIN   #__wrecruit_jobs AS jobs  ON  jobs.id=featuredjobs.jobid
		LEFT JOIN #__wrecruit_employerpackages AS package ON package.id=featuredjobs.packageid
		LEFT JOIN #__wrecruit_companies AS company ON  company.id=jobs.companyid
		WHERE featuredjobs.status = 0";

		if ($searchtitle) $query .= " AND LOWER(jobs.title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchtitle, true ).'%', false );
		if ($searchcompany) $query .= " AND LOWER(company.name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchcompany, true ).'%', false );
		if ($searchemployerpackage) $query .= " AND LOWER(package.title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchemployerpackage, true ).'%', false );

		$query .= " ORDER BY jobs.created DESC";

		//echo $query;
                $db->setQuery($query,$limitstart, $limit);
                $featuredjobs = $db->loadObjectList();
                $lists = array();

                $job_type = $this->getJobType(JText::_('JS_SELECT_JOB_TYPE'));
                $jobstatus = $this->getJobStatus(JText::_('JS_SELECT_JOB_STATUS'));

                $job_categories = $this->getCategories(JText::_('JS_SELECT_JOB_CATEGORY'),'');
                if ($searchtitle) $lists['searchtitle'] = $searchtitle;
                if ($searchcompany) $lists['searchcompany'] = $searchcompany;
                if ($searchemployerpackage) $lists['searchemployerpackage'] = $searchemployerpackage;


		$result[0] = $featuredjobs;
		$result[1] = $total;
		$result[2] = $lists;
		return $result;
	}
	function & getFeaturedJobId($jobid,$c_id)
	{
		if (is_numeric($jobid) == false) return false;
		if (is_numeric($c_id) == false) return false;
		$db = & JFactory :: getDBO();
		$result = array();

		$query = "SELECT featuredjob.*,job.title AS jobtitle
		FROM #__wrecruit_featuredjobs AS featuredjob
		JOIN #__wrecruit_jobs AS job ON job.id=featuredjob.jobid
		 WHERE featuredjob.id=".$c_id;
		//echo $query;
		$db->setQuery($query);
		$featuredjob = $db->loadObject();

		if ( isset($featuredjob) ){
			$lists['employerpackage'] = JHTML::_('select.genericList', $this->getEmployerPackageForCombo(''), 'packageid', 'class="inputbox required" '. '', 'value', 'text', $featuredjob->packageid);

		}else{
			$lists['employerpackage'] = JHTML::_('select.genericList', $this->getEmployerPackageForCombo(''), 'packageid', 'class="inputbox required" '. '', 'value', 'text', '');
	}
		$query = "SELECT job.title AS jobtitle
		 FROM #__wrecruit_jobs AS job
		 WHERE job.id=".$jobid;

		$db->setQuery($query);
		$jobtitle = $db->loadResult();


		$result[0] = $featuredjob;
		$result[1] = $lists;
		$result[2] = $jobtitle;
		return $result;
	}
	function storeFeaturedJob($uid, $jobid)
	{
		if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		if (is_numeric($jobid) == false) return false;
		$row = & $this->getTable('featuredjob');

		$data = JRequest :: get('post');

		$row->uid=$data['uid'];

		$row->created = date('Y-m-d H:i:s');

		$data['startdate'] =  date('Y-m-d H:i:s',strtotime($data['startdate']));
		$data['enddate'] =  date('Y-m-d H:i:s',strtotime($data['enddate']));

		if (!$row->bind($data))	{
			$this->setError($this->_db->getErrorMsg());
			echo $this->_db->getErrorMsg();
			return false;
		}

		if ($data['id'] == ''){ // only for new
			$result=$this->featuredJobValidation($uid, $jobid);
			if ($result == false)
			{
				return 6;
			}
		}

		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			echo $this->_db->getErrorMsg();
			return false;
		}
		return true;
	}

	function featuredJobValidation($uid, $jobid)
	{

		$db =& JFactory::getDBO();
		if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;

		$query = "SELECT COUNT(featuredjob.id)
		FROM #__wrecruit_featuredjobs  AS featuredjob
		JOIN #__wrecruit_employerpackages AS package ON package.id=featuredjob.packageid
		WHERE featuredjob.uid = ".$uid ." AND featuredjob.jobid = ".$jobid."
		AND DATE_ADD(featuredjob.created,INTERVAL package.featuredjobsexpireindays DAY) >= CURDATE()";

		//echo '<br>sql '.$query;
		$db->setQuery( $query );
		$result = $db->loadResult();
		//echo '<br>r'.$result;
		if ($result == 0)
			return true;
		else
			return false;

	}

	function deleteFeaturedJob()
	{
		$cids = JRequest :: getVar('cid', array (0), 'post', 'array');
		$row = & $this->getTable('featuredjob');
		$deleteall = 1;
		foreach ($cids as $cid)	{

				if (!$row->delete($cid)){
					$this->setError($row->getErrorMsg());
					return false;
				}

		}
		return true;

	}

	function & getGoldCompanies($searchcompany,$searchemployerpackage,$searchcountry,$limitstart, $limit)
	{
		$db = & JFactory :: getDBO();
		$result = array();
		$query = "SELECT COUNT(goldcompany.id)
		FROM #__wrecruit_goldcompanies AS goldcompany
		JOIN  #__wrecruit_employerpackages AS package  ON  package.id=goldcompany.packageid
		JOIN  #__wrecruit_companies AS company  ON  company.id=goldcompany.companyid
		WHERE goldcompany.status <>0";
		if ($searchcompany) $query .= " AND LOWER(company.name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchcompany, true ).'%', false );
		if ($searchemployerpackage) $query .= " AND LOWER(package.title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchemployerpackage, true ).'%', false );
		if ($searchcountry) $query .= " AND company.country = ".$db->Quote($searchcountry);
		$db->setQuery($query);
		$total = $db->loadResult();
		if ( $total <= $limitstart ) $limitstart = 0;

		$query = "SELECT goldcompany.*,company.name,country.name AS countryname,package.title AS packagetitle
		FROM #__wrecruit_goldcompanies AS goldcompany
		JOIN   #__wrecruit_companies AS company  ON  company.id=goldcompany.companyid
		JOIN   #__wrecruit_employerpackages AS package  ON  package.id=goldcompany.packageid
		JOIN #__wrecruit_countries AS country ON company.country = country.code
		WHERE goldcompany.status <> 0";
		if ($searchcompany) $query .= " AND LOWER(company.name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchcompany, true ).'%', false );
		if ($searchemployerpackage) $query .= " AND LOWER(package.title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchemployerpackage, true ).'%', false );
		if ($searchcountry) $query .= " AND company.country = ".$db->Quote($searchcountry);
		//echo $query;
		$db->setQuery($query,$limitstart, $limit);
		$goldcompany = $db->loadObjectList();

		$lists=array();

		$countries = $this->getCountries(JText::_('JS_SELECT_COUNTRY'));
		if ($searchcompany) $lists['searchcompany'] = $searchcompany;

		if ($searchemployerpackage) $lists['searchemployerpackage'] = $searchemployerpackage;

		if ($searchcountry)
				$lists['country'] = JHTML::_('select.genericList', $countries, 'searchcountry', 'class="inputbox" '.'onChange="document.adminForm.submit();"', 'value', 'text', $searchcountry);
		else
				$lists['country'] = JHTML::_('select.genericList', $countries, 'searchcountry', 'class="inputbox" '.'onChange="document.adminForm.submit();"', 'value', 'text', '');


		$result[0] = $goldcompany;
		$result[1] = $total;
		$result[2] = $lists;
		return $result;
	}


	function & getAllUnapprovedGoldCompanies($searchcompany,$searchemployerpackage,$searchcountry,$limitstart, $limit)
	{
		$db = & JFactory :: getDBO();
		$result = array();
		$query = "SELECT COUNT(goldcompany.id)
		FROM #__wrecruit_goldcompanies AS goldcompany
		JOIN  #__wrecruit_employerpackages AS package  ON  package.id=goldcompany.packageid
		JOIN  #__wrecruit_companies AS company  ON  company.id=goldcompany.companyid
		WHERE goldcompany.status = 0";
		if ($searchcompany) $query .= " AND LOWER(company.name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchcompany, true ).'%', false );
		if ($searchemployerpackage) $query .= " AND LOWER(package.title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchemployerpackage, true ).'%', false );
		if ($searchcountry) $query .= " AND company.country = ".$db->Quote($searchcountry);
		$db->setQuery($query);
		$total = $db->loadResult();
		if ( $total <= $limitstart ) $limitstart = 0;

		$query = "SELECT goldcompany.*,company.name,country.name AS countryname,package.title AS packagetitle
		FROM #__wrecruit_goldcompanies AS goldcompany
		JOIN   #__wrecruit_companies AS company  ON  company.id=goldcompany.companyid
		JOIN   #__wrecruit_employerpackages AS package  ON  package.id=goldcompany.packageid
		JOIN #__wrecruit_countries AS country ON company.country = country.code
		WHERE goldcompany.status = 0";
		if ($searchcompany) $query .= " AND LOWER(company.name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchcompany, true ).'%', false );
		if ($searchemployerpackage) $query .= " AND LOWER(package.title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchemployerpackage, true ).'%', false );
		if ($searchcountry) $query .= " AND company.country = ".$db->Quote($searchcountry);
		//echo $query;
		$db->setQuery($query,$limitstart, $limit);
		$goldcompany = $db->loadObjectList();

		$lists=array();

		$countries = $this->getCountries(JText::_('JS_SELECT_COUNTRY'));
		if ($searchcompany) $lists['searchcompany'] = $searchcompany;

		if ($searchemployerpackage) $lists['searchemployerpackage'] = $searchemployerpackage;

		if ($searchcountry)
				$lists['country'] = JHTML::_('select.genericList', $countries, 'searchcountry', 'class="inputbox" '.'onChange="document.adminForm.submit();"', 'value', 'text', $searchcountry);
		else
				$lists['country'] = JHTML::_('select.genericList', $countries, 'searchcountry', 'class="inputbox" '.'onChange="document.adminForm.submit();"', 'value', 'text', '');


		$result[0] = $goldcompany;
		$result[1] = $total;
		$result[2] = $lists;
		return $result;
	}



	function & getGoldCompanyId($companyid,$c_id)
	{

		if (is_numeric($companyid) == false) return false;
		if (is_numeric($c_id) == false) return false;

		$db = & JFactory :: getDBO();
		$result = array();

		$query = "SELECT goldcompany.*,company.name AS companyname
		FROM #__wrecruit_goldcompanies AS goldcompany
		LEFT JOIN #__wrecruit_companies AS company ON company.id=goldcompany.companyid
		 WHERE goldcompany.id=".$c_id;
		//echo $query;
		$db->setQuery($query);
		$goldcompany = $db->loadObject();

		if ( isset($goldcompany) ){
			$lists['companies'] = JHTML::_('select.genericList', $this->getCompany(''), 'companyid', 'class="inputbox required" '. '', 'value', 'text',$goldcompany->companyid );
			$lists['employerpackage'] = JHTML::_('select.genericList', $this->getEmployerPackageForCombo(''), 'packageid', 'class="inputbox required" '. '', 'value', 'text', $goldcompany->packageid);

		}else{
			$lists['companies'] = JHTML::_('select.genericList', $this->getCompany(''), 'companyid', 'class="inputbox required" '. '', 'value', 'text', '');
			$lists['employerpackage'] = JHTML::_('select.genericList', $this->getEmployerPackageForCombo(''), 'packageid', 'class="inputbox required" '. '', 'value', 'text', '');
	}

		$query = "SELECT company.name AS companyname
		FROM #__wrecruit_companies AS company
		WHERE company.id=".$companyid;
		//echo $query;
		$db->setQuery($query);
		$companyname = $db->loadResult();




		$result[0] = $goldcompany;
		$result[1] = $lists;
		$result[2] = $companyname;
		return $result;
	}



	function storeGoldCompany($uid, $companyid)
	{
		if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		if (is_numeric($companyid) == false) return false;
		$row = & $this->getTable('goldcompany');

		$data = JRequest :: get('post');

		$row->uid=$uid;
		$row->created=date('Y-m-d H:i:s');
		$data['startdate'] =  date('Y-m-d H:i:s',strtotime($data['startdate']));
		$data['enddate'] =  date('Y-m-d H:i:s',strtotime($data['enddate']));
		if (!$row->bind($data))	{
			$this->setError($this->_db->getErrorMsg());
			echo $this->_db->getErrorMsg();
			return false;
		}
		if ($data['id'] == ''){ // only for new
			$result=$this->goldCompanyValidation($uid, $companyid);
			if ($result == false) return 6;
		}
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			echo $this->_db->getErrorMsg();
			return false;
		}
		return true;
	}
	function goldCompanyValidation($uid, $companyid)
	{

		$db =& JFactory::getDBO();
		if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;

		$query = "SELECT COUNT(gold.id)
		FROM #__wrecruit_goldcompanies  AS gold
		JOIN #__wrecruit_employerpackages AS package ON package.id=gold.packageid
		WHERE gold.uid = ".$uid ." AND gold.companyid = ".$companyid."
		AND DATE_ADD(gold.created,INTERVAL package.goldcompaniesexpireindays DAY) >= CURDATE()";

		//echo '<br>sql '.$query;
		$db->setQuery( $query );
		$result = $db->loadResult();
		//echo '<br>r'.$result;
		if ($result == 0)
			return true;
		else
			return false;

	}

	function deleteGoldCompany()
	{
		$cids = JRequest :: getVar('cid', array (0), 'post', 'array');
		$row = & $this->getTable('goldcompany');
		$deleteall = 1;
		foreach ($cids as $cid)	{

				if (!$row->delete($cid)){
					$this->setError($row->getErrorMsg());
					return false;
				}

		}
		return true;

	}

	function & getFeaturedCompanies($searchcompany,$searchemployerpackage,$searchcountry,$limitstart, $limit)
	{
		$db = & JFactory :: getDBO();
		$result = array();
		$query = "SELECT COUNT(featuredcompany.id)
		FROM #__wrecruit_featuredcompanies AS featuredcompany
		JOIN #__wrecruit_employerpackages  AS package ON featuredcompany.packageid = package.id
		JOIN   #__wrecruit_companies AS company  ON  company.id=featuredcompany.companyid
		WHERE featuredcompany.status <> 0";
		if ($searchcompany) $query .= " AND LOWER(company.name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchcompany, true ).'%', false );
		if ($searchemployerpackage) $query .= " AND LOWER(package.title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchemployerpackage, true ).'%', false );
		if ($searchcountry) $query .= " AND company.country = ".$db->Quote($searchcountry);
		$db->setQuery($query);
		$total = $db->loadResult();
		if ( $total <= $limitstart ) $limitstart = 0;

		$query = "SELECT featuredcompany.*,company.name,company.url, package.title AS packagetitle , country.name AS countryname
		FROM #__wrecruit_featuredcompanies AS featuredcompany
		JOIN   #__wrecruit_companies AS company  ON  company.id=featuredcompany.companyid
		JOIN #__wrecruit_employerpackages  AS package ON featuredcompany.packageid = package.id
		JOIN #__wrecruit_countries AS country ON company.country = country.code
		WHERE featuredcompany.status <> 0";
		if ($searchcompany) $query .= " AND LOWER(company.name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchcompany, true ).'%', false );
		if ($searchemployerpackage) $query .= " AND LOWER(package.title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchemployerpackage, true ).'%', false );
		if ($searchcountry) $query .= " AND company.country = ".$db->Quote($searchcountry);
		//echo $query;
		$db->setQuery($query,$limitstart, $limit);
		$featuredcompany = $db->loadObjectList();
		$lists = array();

		$job_categories = $this->getCategories(JText::_('JS_SELECT_JOB_CATEGORY'),'');
		$countries = $this->getCountries(JText::_('JS_SELECT_COUNTRY'));
		if ($searchcompany) $lists['searchcompany'] = $searchcompany;
		if ($searchemployerpackage) $lists['searchemployerpackage'] = $searchemployerpackage;
		if ($searchcountry)
				$lists['country'] = JHTML::_('select.genericList', $countries, 'searchcountry', 'class="inputbox" '.'onChange="document.adminForm.submit();"', 'value', 'text', $searchcountry);
		else
				$lists['country'] = JHTML::_('select.genericList', $countries, 'searchcountry', 'class="inputbox" '.'onChange="document.adminForm.submit();"', 'value', 'text', '');

		$result[0] = $featuredcompany;
		$result[1] = $total;
		$result[2] = $lists;
		return $result;
	}

	function & getAllUnapprovedFeaturedCompanies($searchcompany,$searchemployerpackage,$searchcountry,$limitstart, $limit)
	{
		$db = & JFactory :: getDBO();
		$result = array();
		$query = "SELECT COUNT(featuredcompany.id)
		FROM #__wrecruit_featuredcompanies AS featuredcompany
		JOIN #__wrecruit_employerpackages  AS package ON featuredcompany.packageid = package.id
		JOIN   #__wrecruit_companies AS company  ON  company.id=featuredcompany.companyid
		WHERE featuredcompany.status = 0";
		if ($searchcompany) $query .= " AND LOWER(company.name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchcompany, true ).'%', false );
		if ($searchemployerpackage) $query .= " AND LOWER(package.title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchemployerpackage, true ).'%', false );
		if ($searchcountry) $query .= " AND company.country = ".$db->Quote($searchcountry);
		$db->setQuery($query);
		$total = $db->loadResult();
		if ( $total <= $limitstart ) $limitstart = 0;

		$query = "SELECT featuredcompany.*,company.name,company.url, package.title AS packagetitle , country.name AS countryname
		FROM #__wrecruit_featuredcompanies AS featuredcompany
		JOIN   #__wrecruit_companies AS company  ON  company.id=featuredcompany.companyid
		JOIN #__wrecruit_employerpackages  AS package ON featuredcompany.packageid = package.id
		JOIN #__wrecruit_countries AS country ON company.country = country.code
		WHERE featuredcompany.status = 0";
		if ($searchcompany) $query .= " AND LOWER(company.name) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchcompany, true ).'%', false );
		if ($searchemployerpackage) $query .= " AND LOWER(package.title) LIKE ".$db->Quote( '%'.$db->getEscaped( $searchemployerpackage, true ).'%', false );
		if ($searchcountry) $query .= " AND company.country = ".$db->Quote($searchcountry);
		//echo $query;
		$db->setQuery($query,$limitstart, $limit);
		$featuredcompany = $db->loadObjectList();
		$lists = array();

		$job_categories = $this->getCategories(JText::_('JS_SELECT_JOB_CATEGORY'),'');
		$countries = $this->getCountries(JText::_('JS_SELECT_COUNTRY'));
		if ($searchcompany) $lists['searchcompany'] = $searchcompany;
		if ($searchemployerpackage) $lists['searchemployerpackage'] = $searchemployerpackage;
		if ($searchcountry)
				$lists['country'] = JHTML::_('select.genericList', $countries, 'searchcountry', 'class="inputbox" '.'onChange="document.adminForm.submit();"', 'value', 'text', $searchcountry);
		else
				$lists['country'] = JHTML::_('select.genericList', $countries, 'searchcountry', 'class="inputbox" '.'onChange="document.adminForm.submit();"', 'value', 'text', '');

		$result[0] = $featuredcompany;
		$result[1] = $total;
		$result[2] = $lists;
		return $result;
	}




	function & getFeaturedCompanyId($companyid,$c_id)
	{
		if (is_numeric($companyid) == false) return false;
		if (is_numeric($c_id) == false) return false;

        	$db = & JFactory :: getDBO();
		$result = array();

		$query = "SELECT featuredcompany.*,company.name AS companyname
		FROM #__wrecruit_featuredcompanies AS featuredcompany
		LEFT JOIN #__wrecruit_companies AS company ON company.id=featuredcompany.companyid
		 WHERE featuredcompany.id=".$c_id;
		//echo $query;
		$db->setQuery($query);
		$featuredcompany = $db->loadObject();

		if ( isset($featuredcompany) ){
			$lists['companies'] = JHTML::_('select.genericList', $this->getCompany(''), 'companyid', 'class="inputbox required" '. '', 'value', 'text',$featuredcompany->companyid );
			$lists['employerpackage'] = JHTML::_('select.genericList', $this->getEmployerPackageForCombo(''), 'packageid', 'class="inputbox required" '. '', 'value', 'text', $featuredcompany->packageid);

		}else{
			$lists['companies'] = JHTML::_('select.genericList', $this->getCompany(''), 'companyid', 'class="inputbox required" '. '', 'value', 'text', '');
			$lists['employerpackage'] = JHTML::_('select.genericList', $this->getEmployerPackageForCombo(''), 'packageid', 'class="inputbox required" '. '', 'value', 'text', '');
		}

		$query = "SELECT company.name AS companyname
		FROM #__wrecruit_companies AS company
		WHERE company.id=".$companyid;
		//echo $query;
		$db->setQuery($query);
		$companyname = $db->loadResult();


		$result[0] = $featuredcompany;
		$result[1] = $lists;
		$result[2] = $companyname;
		return $result;

	}


	function storeFeaturedCompany($companyid,$uid)
	{
		if (is_numeric($companyid) == false) return false;
		if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		$row = & $this->getTable('featuredcompany');

		$data = JRequest :: get('post');
		$row->uid=$uid;
		$row->created=date('Y-m-d H:i:s');
		$data['startdate'] =  date('Y-m-d H:i:s',strtotime($data['startdate']));
		$data['enddate'] =  date('Y-m-d H:i:s',strtotime($data['enddate']));
		if (!$row->bind($data))	{
			$this->setError($this->_db->getErrorMsg());
			echo $this->_db->getErrorMsg();
			return false;
		}
		if ($data['id'] == ''){ // only for new
			$result=$this->featuredCompanyValidation($uid, $companyid);
			if ($result == false) return 6;
		}
		if (!$row->store())	{
			$this->setError($this->_db->getErrorMsg());
			echo $this->_db->getErrorMsg();
			return false;
		}
		return true;
	}

	function featuredCompanyValidation($uid, $companyid)
	{

		if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
		if (is_numeric($companyid) == false) return false;
		$db =& JFactory::getDBO();

		$query = "SELECT COUNT(featuredcompany.id)
		FROM #__wrecruit_featuredcompanies  AS featuredcompany
		JOIN #__wrecruit_employerpackages AS package ON package.id=featuredcompany.packageid
		WHERE featuredcompany.uid = ".$uid ." AND featuredcompany.companyid = ".$companyid."
		AND DATE_ADD(featuredcompany.created,INTERVAL package.featuredcompaniesexpireindays DAY) >= CURDATE()";

		//echo '<br>sql '.$query;
		$db->setQuery( $query );
		$result = $db->loadResult();
		//echo '<br>r'.$result;
		if ($result == 0)
			return true;
		else
			return false;

	}

	function deleteFeaturedCompany()
	{
		$cids = JRequest :: getVar('cid', array (0), 'post', 'array');
		$row = & $this->getTable('featuredcompany');
		$deleteall = 1;
		foreach ($cids as $cid)	{

				if (!$row->delete($cid)){
					$this->setError($row->getErrorMsg());
					return false;
				}

		}
		return true;

	}
	function goldCompanyApprove($companyid)
	{
		if (is_numeric($companyid) == false) return false;
		$db =& JFactory::getDBO();

		$query = "UPDATE #__wrecruit_goldcompanies SET status = 1 WHERE id = ".$companyid;
		//echo '<br>sql '.$query;
		$db->setQuery( $query );
		if (!$db->query()) {
			return false;
		}
		//return $this->sendMail(2, 1, $job_id);
		return true;
	}

	function goldCompanyReject($companyid)
	{
		if (is_numeric($companyid) == false) return false;
		$db =& JFactory::getDBO();

		$query = "UPDATE #__wrecruit_goldcompanies SET status = -1 WHERE id = ".$companyid;
		//echo '<br>sql '.$query;
		$db->setQuery( $query );
		if (!$db->query()) {
			return false;
		}
		//return $this->sendMail(2, 1, $job_id);
		return true;
	}



	function featuredCompanyApprove($companyid)
	{
		if (is_numeric($companyid) == false) return false;
		$db =& JFactory::getDBO();

		$query = "UPDATE #__wrecruit_featuredcompanies SET status = 1 WHERE id = ".$companyid;
		//echo '<br>sql '.$query;
		$db->setQuery( $query );
		if (!$db->query()) {
			return false;
		}
		//return $this->sendMail(2, 1, $job_id);
		return true;
	}

	function featuredCompanyReject($companyid)
	{
		if (is_numeric($companyid) == false) return false;
		$db =& JFactory::getDBO();

		$query = "UPDATE #__wrecruit_featuredcompanies SET status = -1 WHERE id = ".$companyid;
		//echo '<br>sql '.$query;
		$db->setQuery( $query );
		if (!$db->query()) {
			return false;
		}
		//return $this->sendMail(2, 1, $job_id);
		return true;
	}



	function featuredJobApprove($jobid)
	{
		if (is_numeric($jobid) == false) return false;
		$db =& JFactory::getDBO();

		$query = "UPDATE #__wrecruit_featuredjobs SET status = 1 WHERE id = ".$jobid;
		//echo '<br>sql '.$query;
		$db->setQuery( $query );
		if (!$db->query()) {
			return false;
		}
		//return $this->sendMail(2, 1, $job_id);
		return true;
	}

	function featuredJobReject($jobid)
	{
		if (is_numeric($jobid) == false) return false;
		$db =& JFactory::getDBO();

		$query = "UPDATE #__wrecruit_featuredjobs SET status = -1 WHERE id = ".$jobid;
		//echo '<br>sql '.$query;
		$db->setQuery( $query );
		if (!$db->query()) {
			return false;
		}
		//return $this->sendMail(2, 1, $job_id);
		return true;
	}


	function goldJobApprove($jobid)
	{
		if (is_numeric($jobid) == false) return false;
		$db =& JFactory::getDBO();

		$query = "UPDATE #__wrecruit_goldjobs SET status = 1 WHERE id = ".$jobid;
		//echo '<br>sql '.$query;
		$db->setQuery( $query );
		if (!$db->query()) {
			return false;
		}
		//return $this->sendMail(2, 1, $job_id);
		return true;
	}

	function goldJobReject($jobid)
	{
		if (is_numeric($jobid) == false) return false;
		$db =& JFactory::getDBO();

		$query = "UPDATE #__wrecruit_goldjobs SET status = -1 WHERE id = ".$jobid;
		//echo '<br>sql '.$query;
		$db->setQuery( $query );
		if (!$db->query()) {
			return false;
		}
		//return $this->sendMail(2, 1, $job_id);
		return true;
	}


	function featuredResumeApprove($resumeid)
	{
		if (is_numeric($jobid) == false) return false;
		$db =& JFactory::getDBO();

		$query = "UPDATE #__wrecruit_featuredresumes SET status = 1 WHERE id = ".$resumeid;
		//echo '<br>sql '.$query;
		$db->setQuery( $query );
		if (!$db->query()) {
			return false;
		}
		//return $this->sendMail(2, 1, $job_id);
		return true;
	}

	function featuredResumeReject($resumeid)
	{
		if (is_numeric($resumeid) == false) return false;
		$db =& JFactory::getDBO();

		$query = "UPDATE #__wrecruit_featuredresumes SET status = -1 WHERE id = ".$resumeid;
		//echo '<br>sql '.$query;
		$db->setQuery( $query );
		if (!$db->query()) {
			return false;
		}
		//return $this->sendMail(2, 1, $job_id);
		return true;
	}

	function goldResumeApprove($resumeid)
	{
		if (is_numeric($resumeid) == false) return false;
		$db =& JFactory::getDBO();

		$query = "UPDATE #__wrecruit_goldresumes SET status = 1 WHERE id = ".$resumeid;
		//echo '<br>sql '.$query;
		$db->setQuery( $query );
		if (!$db->query()) {
			return false;
		}
		//return $this->sendMail(2, 1, $job_id);
		return true;
	}

	function goldResumeReject($resumeid)
	{
		if (is_numeric($resumeid) == false) return false;
		$db =& JFactory::getDBO();

		$query = "UPDATE #__wrecruit_goldresumes SET status = -1 WHERE id = ".$resumeid;
		//echo '<br>sql '.$query;
		$db->setQuery( $query );
		if (!$db->query()) {
			return false;
		}
		//return $this->sendMail(2, 1, $job_id);
		return true;
	}

// Payment System End;

// Payment Package Code
	function getPaymentStatus( $title ){
			$db =& JFactory::getDBO();
			$AppRej = array();
			if($title)
				$AppRej[] =  array('value' => '','text' => $title);

			$AppRej[] =  array('value' => 1,	'text' => JText::_('JS_VERIFIED'));
			$AppRej[] =  array('value' => -1,	'text' => JText::_('JS_NOT_VERIFIED'));

		return $AppRej;
	}


	function jobseekerPaymentApprove($packageid)
	{
		if (is_numeric($packageid) == false) return false;
		$db =& JFactory::getDBO();

		$query = "UPDATE #__wrecruit_jobseekerpaymenthistory SET transactionverified = 1, status=1 WHERE id = ".$packageid;
		//echo '<br>sql '.$query;
		$db->setQuery( $query );
		if (!$db->query()) {
			return false;
		}
		//return $this->sendMail(2, 1, $job_id);
		return true;
	}


	function jobseekerPaymentReject($packageid)
	{
		if (is_numeric($packageid) == false) return false;
		$db =& JFactory::getDBO();

		$query = "UPDATE #__wrecruit_jobseekerpaymenthistory SET transactionverified = -1 , status= -1 WHERE id = ".$packageid;
		//echo '<br>sql '.$query;
		$db->setQuery( $query );
		if (!$db->query()) {
			return false;
		}
		//return $this->sendMail(2, -1, $job_id);
		return true;
	}


	function employerPaymentApprove($packageid)
	{
		if (is_numeric($packageid) == false) return false;
		$db =& JFactory::getDBO();

		$query = "UPDATE #__wrecruit_employerpaymenthistory SET transactionverified = 1 , status=1 WHERE id = ".$packageid;
		//echo '<br>sql '.$query;
		$db->setQuery( $query );
		if (!$db->query()) {
			return false;
		}
		//return $this->sendMail(2, 1, $job_id);
		return true;
	}


	function employerPaymentReject($packageid)
	{
		if (is_numeric($packageid) == false) return false;
		$db =& JFactory::getDBO();

		$query = "UPDATE #__wrecruit_employerpaymenthistory SET transactionverified = -1  , status= -1 WHERE id = ".$packageid;
		//echo '<br>sql '.$query;
		$db->setQuery( $query );
		if (!$db->query()) {
			return false;
		}
		//return $this->sendMail(2, -1, $job_id);
		return true;
	}

	function & getEmployerPackages($limitstart, $limit)
	{
		$db = & JFactory :: getDBO();
		$result = array();
		$query = "SELECT COUNT(id) FROM #__wrecruit_employerpackages ";
		$db->setQuery($query);
		$total = $db->loadResult();
		if ( $total <= $limitstart ) $limitstart = 0;

		$query = "SELECT * FROM #__wrecruit_employerpackages  ORDER BY id ASC";
		//echo $query;
		$db->setQuery($query,$limitstart, $limit);
		$packages = $db->loadObjectList();

		$result[0] = $packages;
		$result[1] = $total;
		return $result;
	}

	function & getEmployerPackagebyId($c_id)
	{
		if (is_numeric($c_id) == false) return false;
		$db = & JFactory :: getDBO();
		$query = "SELECT * FROM #__wrecruit_employerpackages WHERE id = ".$c_id;
		$db->setQuery($query);
		$package = $db->loadObject();
		$status = array(
			'0' => array('value' => 0,'text' => JText::_('JS_UNPUBLISHED')),
			'1' => array('value' => 1,'text' => JText::_('JS_PUBLISHED')),);
		$unpublishjobtype = array(
			'0' => array('value' => 1,'text' => JText::_('JS_DAYS')),
			'1' => array('value' => 2,'text' => JText::_('JS_WEEKS')),
			'2' => array('value' => 3,'text' => JText::_('JS_MONTHS')),);
		$type = array(
			'0' => array('value' => 1,'text' => JText::_('Amount')),
			'1' => array('value' => 2,'text' => JText::_('%')),);

		$yesNo = array(
			'0' => array('value' => 1,'text' => JText::_('yes')),
			'1' => array('value' => 0,'text' => JText::_('No')),);

		if ( isset($package) ){
			$lists['status'] = JHTML::_('select.genericList', $status, 'status', 'class="inputbox required" '. '', 'value', 'text', $package->status);
			$lists['unpublishjobtype'] = JHTML::_('select.genericList', $unpublishjobtype, 'enforcestoppublishjobtype', 'class="inputbox required" '. '', 'value', 'text', $package->enforcestoppublishjobtype);
			$lists['type'] = JHTML::_('select.genericList', $type, 'discounttype', 'class="inputbox required" '. '', 'value', 'text', $package->discounttype);
			$lists['resumesearch'] = JHTML::_('select.genericList', $yesNo, 'resumesearch', 'class="inputbox required" '. '', 'value', 'text', $package->resumesearch);
			$lists['saveresumesearch'] = JHTML::_('select.genericList', $yesNo, 'saveresumesearch', 'class="inputbox required" '. '', 'value', 'text', $package->saveresumesearch);
			$lists['messages'] = JHTML::_('select.genericList', $yesNo, 'messageallow', 'class="inputbox required" '. '', 'value', 'text', $package->messageallow);

		}else{
			$lists['status'] = JHTML::_('select.genericList', $status, 'status', 'class="inputbox required" '. '', 'value', 'text', '');
			$lists['unpublishjobtype'] = JHTML::_('select.genericList', $unpublishjobtype, 'unpublishjobtype', 'class="inputbox required" '. '', 'value', 'text', '');
			$lists['type'] = JHTML::_('select.genericList', $type, 'discounttype', 'class="inputbox required" '. '', 'value', 'text', '');
			$lists['resumesearch'] = JHTML::_('select.genericList', $yesNo, 'resumesearch', 'class="inputbox required" '. '', 'value', 'text', '');
			$lists['saveresumesearch'] = JHTML::_('select.genericList', $yesNo, 'saveresumesearch', 'class="inputbox required" '. '', 'value', 'text', '');
			$lists['messages'] = JHTML::_('select.genericList', $yesNo, 'messageallow', 'class="inputbox required" '. '', 'value', 'text', '' );



                }

		$result[0]=$package;
		$result[1]=$lists;
                $result[2]=$this->getConfigByFor('payment');

		return $result;

	}
	function &getPaymentReport($buyername,$paymentfor,$searchpaymentstatus,$searchstartdate,$searchenddate,$limitstart, $limit)
	{
		$db = & JFactory :: getDBO();
		$result = array();
		if(! isset($this->_config)) $this->getConfig();
		foreach($this->_config AS $config){
			if($config->configname == 'date_format') $dateformat = $config->configvalue;
		}	
		$companywherequery = '';
                $ewherequery = '';
                $jwherequery = '';
                /*
                if ($buyername) {
                    if ($paymentfor == 'both'){

                    }elseif ($paymentfor == 'employer'){
                        $wherequery = "  JOIN #__wrecruit_companies AS bcompany ON payment.uid = bcompany.uid AND bcompany.name like ".$db->Quote(  $buyername );
                        $companywherequery = "  AND company.name like ".$db->Quote(  $buyername );
                    }elseif ($paymentfor == 'jobseeker'){
                        $wherequery = "  JOIN #__wrecruit_resume AS bresume ON payment.uid = bresume.uid AND (
                            LOWER(bresume.first_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $buyername, true ).'%', false )."
                            OR LOWER(bresume.last_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $buyername, true ).'%', false )."
                            OR LOWER(bresume.middle_name) LIKE ".$db->Quote( '%'.$db->getEscaped( $buyername, true ).'%', false )."
                             )";

                        $companywherequery = "  AND company.name like ".$db->Quote(  $buyername );
                    }
                }
                 */
		if (!$searchstartdate){
			$searchstartdate = date('Y-m-d',strtotime(date("Y-m-d")." -1 month"));
			$searchenddate = date('Y-m-d',strtotime(date("Y-m-d")." +1 day"));//include today
		}else{
			$searchstartdate = date('Y-m-d',strtotime($searchstartdate));
			$searchenddate = date('Y-m-d',strtotime($searchenddate));
		}

		if ($paymentfor == '') $paymentfor = 'both';
                if ($paymentfor == 'both'){
			$clause = " WHERE ";
			if ($searchpaymentstatus) {
                            $ewherequery .= $clause."  epayment.transactionverified = ".$searchpaymentstatus;
                            $jwherequery .= $clause."  jpayment.transactionverified = ".$searchpaymentstatus;
                            $clause = " AND ";
                        }
                        if ($searchstartdate AND $searchenddate){
                             $ewherequery .= $clause."  epayment.created BETWEEN ".$db->Quote(  $searchstartdate )." AND ".$db->Quote(  $searchenddate );
                             $jwherequery .= $clause."  jpayment.created BETWEEN ".$db->Quote(  $searchstartdate )." AND ".$db->Quote(  $searchenddate );
                             $clause = " AND ";
			}
                }else{
			$clause = " WHERE ";
			if ($searchpaymentstatus) {
                            $wherequery .= $clause."  payment.transactionverified = ".$searchpaymentstatus;
                            $clause = " AND ";
                        }
                        if ($searchstartdate AND $searchenddate){
                             $wherequery .= $clause."  payment.created BETWEEN ".$db->Quote(  $searchstartdate )." AND ".$db->Quote(  $searchenddate );
                             $clause = " AND ";
			}
                }
		if($paymentfor=='employer'){
			$totalquery = "SELECT COUNT(payment.id)
					FROM #__wrecruit_employerpaymenthistory AS payment
					JOIN #__wrecruit_employerpackages AS package ON payment.packageid = package.id";

			$query = "SELECT payment.uid,payment.packageid,payment.packagetitle, 'Employer' AS packagefor, payment.payer_firstname,payment.paidamount,payment.transactionverified,payment.created
                                        ,(SELECT company.name FROM #__wrecruit_companies AS company WHERE payment.uid = company.uid ". $companywherequery ." LIMIT 1 ) AS buyername
					FROM #__wrecruit_employerpaymenthistory AS payment
					JOIN #__wrecruit_employerpackages AS package ON payment.packageid = package.id";

                        $totalquery = $totalquery . $wherequery;
                        $query = $query . $wherequery.' ORDER BY payment.created DESC';
		}elseif($paymentfor=='jobseeker'){
			$totalquery = "SELECT COUNT(payment.id)
					FROM #__wrecruit_jobseekerpaymenthistory AS payment
					JOIN #__wrecruit_jobseekerpackages AS package ON payment.packageid = package.id";

			$query = "SELECT payment.uid,payment.packageid,payment.packagetitle, 'Job Seeker' AS packagefor,payment.payer_firstname,payment.paidamount,payment.transactionverified,payment.created
					,(SELECT CONCAT(resume.first_name,' ',resume.last_name) FROM #__wrecruit_resume AS resume WHERE payment.uid = resume.uid LIMIT 1) AS buyername
                                        FROM #__wrecruit_jobseekerpaymenthistory AS payment
					JOIN #__wrecruit_jobseekerpackages AS package ON payment.packageid = package.id";

                        $totalquery = $totalquery . $wherequery;
                        $query = $query . $wherequery.' ORDER BY payment.created DESC';
		}elseif($paymentfor=='both'){
                        $totalquery = "SELECT
					( SELECT COUNT(epayment.id) FROM ".$db->nameQuote('#__wrecruit_employerpaymenthistory')." AS epayment ".$ewherequery.")
					+ ( SELECT COUNT(jpayment.id) FROM ".$db->nameQuote('#__wrecruit_jobseekerpaymenthistory')." AS jpayment ".$jwherequery.")
					AS total ";

			$query = "SELECT epayment.uid,epayment.packageid,epayment.packagetitle, 'Employer' AS packagefor, epayment.payer_firstname,epayment.paidamount,epayment.transactionverified,epayment.created
                                        ,(SELECT company.name FROM #__wrecruit_companies AS company WHERE epayment.uid = company.uid LIMIT 1) AS buyername
					FROM #__wrecruit_employerpaymenthistory AS epayment
					JOIN #__wrecruit_employerpackages AS epackage ON epayment.packageid = epackage.id";
                        $unionquery = "
                            UNION
                            SELECT jpayment.uid,jpayment.packageid,jpayment.packagetitle, 'Job Seeker' AS packagefor,jpayment.payer_firstname,jpayment.paidamount,jpayment.transactionverified,jpayment.created
                                        ,(SELECT CONCAT(resume.first_name,' ',resume.last_name) FROM #__wrecruit_resume AS resume WHERE jpayment.uid = resume.uid LIMIT 1) AS buyername
					FROM #__wrecruit_jobseekerpaymenthistory AS jpayment
					JOIN #__wrecruit_jobseekerpackages AS jpackage ON jpayment.packageid = jpackage.id";
                        $query = $query . $ewherequery . $unionquery . $jwherequery.' ORDER BY created DESC';
		}


                $db->setQuery($totalquery);
                $total = $db->loadResult();

                if ( $total <= $limitstart ) $limitstart = 0;

               //echo $query;
                $db->setQuery($query,$limitstart, $limit);
                $payments = $db->loadObjectList();


                $lists=array();
                $searchstartdate = date($dateformat,strtotime($searchstartdate));
                $searchenddate = date($dateformat,strtotime($searchenddate));

                if ($buyername)  $lists['buyername'] = $buyername;
                if ($searchstartdate)  $lists['searchstartdate'] = $searchstartdate;
                if ($searchenddate)  $lists['searchenddate'] = $searchenddate;

               $paymentforvalues = array(
                '0' => array('value' => 'both',	'text' => JText::_('JS_BOTH')),
                '1' => array('value' => 'employer',	'text' => JText::_('JS_EMPLOYER')),
                '2' => array('value' => 'jobseeker','text' => JText::_('JS_JOBSEEKER')),);

                $lists['paymentfor'] = JHTML::_('select.genericList', $paymentforvalues, 'paymentfor', 'class="inputbox" '.'onChange="document.adminForm.submit();"', 'value', 'text', $paymentfor);

                $paymentstatus = array(
                        '0' => array('value' => '',	'text' => JText::_('JS_SELECT_PAYMENT_STATUS')),
                        '1' => array('value' => 1,'text' => JText::_('JS_VERIFIED')),
                        '2' => array('value' => -1,'text' => JText::_('JS_NOT_VERIFIED')),);

                if ($searchpaymentstatus)
                        $lists['paymentstatus'] = JHTML::_('select.genericList', $paymentstatus, 'searchpaymentstatus', 'class="inputbox" '.'onChange="document.adminForm.submit();"', 'value', 'text', $searchpaymentstatus);
                else
                        $lists['paymentstatus'] = JHTML::_('select.genericList', $paymentstatus, 'searchpaymentstatus', 'class="inputbox" '.'onChange="document.adminForm.submit();"', 'value', 'text', '');

		$result[0] = $payments;
		$result[1] = $total;
		$result[2]= $lists;
		$result[3]= $paymentfor;
		return $result;
	}

	function &getPackagePaymentReport($packageid,$paymentfor,$searchpaymentstatus,$searchstartdate,$searchenddate,$limitstart, $limit)
	{
		$db = & JFactory :: getDBO();
		$result = array();
		$companywherequery = '';
		  if (!$searchstartdate){

                    $searchstartdate = date('Y-m-d',strtotime(date("Y-m-d")." -1 month"));
                    //$searchstartdate = date('CHANGE IT ACCORDIG TO CONFIG',strtotime(date("Y-m-d")." -1 month"));
                    $searchenddate = date('Y-m-d');
                    //$searchenddate = date('CHANGE IT ACCORDIG TO CONFIG');
                }
		if ($searchpaymentstatus) $wherequery .="  AND  payment.transactionverified = ".$searchpaymentstatus;
                if ($searchstartdate AND $searchenddate)  $wherequery .="  AND  payment.created BETWEEN ".$db->Quote(  $searchstartdate )." AND ".$db->Quote(  $searchenddate );

		if($paymentfor=='Employer'){
			$totalquery = "SELECT COUNT(payment.id)
					FROM #__wrecruit_employerpaymenthistory AS payment
					JOIN #__wrecruit_employerpackages AS package ON payment.packageid = package.id
					WHERE payment.packageid=".$packageid;

			$query = "SELECT payment.packageid,payment.packagetitle, 'Employer' AS packagefor, payment.payer_firstname,payment.paidamount,payment.transactionverified,payment.created
                                        ,(SELECT company.name FROM #__wrecruit_companies AS company WHERE payment.uid = company.uid ". $companywherequery ." LIMIT 1 ) AS buyername
					FROM #__wrecruit_employerpaymenthistory AS payment
					JOIN #__wrecruit_employerpackages AS package ON payment.packageid = package.id
					WHERE payment.packageid=".$packageid;

					    $totalquery = $totalquery . $wherequery;
                        $query = $query . $wherequery;

		}elseif($paymentfor=='Job Seeker'){

			$totalquery = "SELECT COUNT(payment.id)
					FROM #__wrecruit_jobseekerpaymenthistory AS payment
					JOIN #__wrecruit_jobseekerpackages AS package ON payment.packageid = package.id
					WHERE payment.packageid = ".$packageid;

			$query = "SELECT payment.packageid,payment.packagetitle, 'Job Seeker' AS packagefor,payment.payer_firstname,payment.paidamount,payment.transactionverified,payment.created
					,(SELECT CONCAT(resume.first_name,' ',resume.last_name) FROM #__wrecruit_resume AS resume WHERE payment.uid = resume.uid LIMIT 1) AS buyername
					FROM #__wrecruit_jobseekerpaymenthistory AS payment
					JOIN #__wrecruit_jobseekerpackages AS package ON payment.packageid = package.id
					WHERE payment.packageid = ".$packageid;

                        $totalquery = $totalquery . $wherequery;
                        $query = $query . $wherequery;

		}



			 $db->setQuery($totalquery);
                $total = $db->loadResult();

                if ( $total <= $limitstart ) $limitstart = 0;

                //echo $totalquery;
                $db->setQuery($query,$limitstart, $limit);
                $payments = $db->loadObjectList();


                $lists=array();

                if ($searchstartdate)  $lists['searchstartdate'] = $searchstartdate;
                if ($searchenddate)  $lists['searchenddate'] = $searchenddate;


                $paymentstatus = array(
                        '0' => array('value' => '',	'text' => JText::_('JS_SELECT_PAYMENT_STATUS')),
                        '1' => array('value' => 1,'text' => JText::_('JS_VERIFIED')),
                        '2' => array('value' => -1,'text' => JText::_('JS_NOT_VERIFIED')),);

                if ($searchpaymentstatus)
                        $lists['paymentstatus'] = JHTML::_('select.genericList', $paymentstatus, 'searchpaymentstatus', 'class="inputbox" '.'onChange="document.adminForm.submit();"', 'value', 'text', $searchpaymentstatus);
                else

					   $lists['paymentstatus'] = JHTML::_('select.genericList', $paymentstatus, 'searchpaymentstatus', 'class="inputbox" '.'onChange="document.adminForm.submit();"', 'value', 'text', '');

			$result[0] = $payments;
			$result[1] = $total;
			$result[2]= $lists;

			return $result;
	}


	function &getEmployerPaymentHistory($searchtitle,$searchprice,$searchpaymentstatus,$limitstart, $limit)
	{
		$db = & JFactory :: getDBO();
		$result = array();
		$query = "SELECT COUNT(payment.id)
				FROM #__wrecruit_employerpaymenthistory AS payment
				JOIN #__wrecruit_employerpackages AS package ON payment.packageid = package.id";


		$clause = " WHERE ";

		if ($searchtitle){
			 $query .= $clause."  payment.packagetitle LIKE ".$db->Quote( '%'.$db->getEscaped( $searchtitle, true ).'%', false );
			$clause = " AND ";
			}
		if ($searchprice) {
			$query .= $clause."payment. packageprice LIKE ".$db->Quote( '%'.$db->getEscaped( $searchprice, true ).'%', false );
			$clause = " AND ";
			}
		if ($searchpaymentstatus)
			$query .= $clause."  payment.transactionverified = ".$searchpaymentstatus;
		//$query .= "ORDER BY payment.packagetitle";

		$db->setQuery($query);
		$total = $db->loadResult();

		if ( $total <= $limitstart ) $limitstart = 0;
		$query = "SELECT payment.*,company.name AS compayname,user.name AS employername
				FROM #__wrecruit_employerpaymenthistory AS payment
				JOIN #__wrecruit_employerpackages AS package ON payment.packageid = package.id
				LEFT JOIN #__wrecruit_companies AS company ON company.id = payment.companyid
				JOIN #__users AS user ON user.id = payment.uid
				";


		$clause = " WHERE ";

		if ($searchtitle){
			 $query .= $clause."  payment.packagetitle LIKE ".$db->Quote( '%'.$db->getEscaped( $searchtitle, true ).'%', false );
			$clause = " AND ";
			}
		if ($searchprice) {
			$query .= $clause."payment. packageprice LIKE ".$db->Quote( '%'.$db->getEscaped( $searchprice, true ).'%', false );
			$clause = " AND ";
			}
		if ($searchpaymentstatus)
			$query .= $clause."  payment.transactionverified = ".$searchpaymentstatus;
		$query .= "ORDER BY payment.created DESC";
		//echo $query;

		$db->setQuery($query,$limitstart, $limit);
		$packages = $db->loadObjectList();
           $lists=array();
	   $paymentstatus = array(
				'0' => array('value' => '',	'text' => JText::_('JS_SELECT_PAYMENT_STATUS')),
				'1' => array('value' => 1,'text' => JText::_('JS_VERIFIED')),
				'2' => array('value' => -1,'text' => JText::_('JS_NOT_VERIFIED')),);

	  // $paymentstatus = $this->getPaymentStatus(' ');

	   if ($searchtitle) $lists['searchtitle'] = $searchtitle;
	   if ($searchprice) $lists['searchprice'] = $searchprice;
	   if ($searchpaymentstatus)
				$lists['paymentstatus'] = JHTML::_('select.genericList', $paymentstatus, 'searchpaymentstatus', 'class="inputbox" '.'onChange="document.adminForm.submit();"', 'value', 'text', $searchpaymentstatus);
			else
				$lists['paymentstatus'] = JHTML::_('select.genericList', $paymentstatus, 'searchpaymentstatus', 'class="inputbox" '.'onChange="document.adminForm.submit();"', 'value', 'text', '');

		$result[0] = $packages;
		$result[1] = $total;
		$result[2]= $lists;
		return $result;
	}

	function & getJobseekerPaymentHistory($searchtitle,$searchprice,$searchpaymentstatus,$limitstart, $limit)
	{
		$db = & JFactory :: getDBO();
		$result = array();
		$query = "SELECT COUNT(payment.id)
				FROM #__wrecruit_jobseekerpaymenthistory AS payment
				JOIN #__wrecruit_jobseekerpackages AS package ON payment.packageid = package.id
				";

		$clause=" WHERE ";
		if ($searchtitle){
		 $query .=$clause. " payment.packagetitle LIKE ".$db->Quote( '%'.$db->getEscaped( $searchtitle, true ).'%', false );
		 $clause=" AND ";
		 }
		if ($searchprice) {
		$query .= $clause."  payment.packageprice LIKE ".$db->Quote( '%'.$db->getEscaped( $searchprice, true ).'%', false );
		$clause=" AND ";
		}
		if ($searchpaymentstatus)
			 $query .= $clause." payment.transactionverified = ".$searchpaymentstatus;

		$db->setQuery($query);
		$total = $db->loadResult();
		if ( $total <= $limitstart ) $limitstart = 0;

		$query = "SELECT payment.*,user.name AS jobseekername
				  FROM #__wrecruit_jobseekerpaymenthistory AS payment
				  JOIN #__wrecruit_jobseekerpackages AS package ON payment.packageid = package.id
				  JOIN #__users AS user ON user.id = payment.uid ";


		$clause="WHERE";
		if ($searchtitle){
		 	$query .= $clause." payment.packagetitle LIKE ".$db->Quote( '%'.$db->getEscaped( $searchtitle, true ).'%', false );
		 	$clause="AND";
		 }
		if ($searchprice) {
			$query .= $clause."  payment.packageprice LIKE ".$db->Quote( '%'.$db->getEscaped( $searchprice, true ).'%', false );
			$clause="AND";
		}
		if ($searchpaymentstatus)
			$query .= $clause." payment.transactionverified = ".$searchpaymentstatus;

                $query .= "ORDER BY payment.created DESC";

		//echo $query;
		$db->setQuery($query,$limitstart, $limit);
		 $this->_application = $db->loadObjectList();

		$lists = array();
		$paymentstatus = array(
				'0' => array('value' => '',	'text' => JText::_('JS_SELECT_PAYMENT_STATUS')),
				'1' => array('value' => 1,'text' => JText::_('JS_VERIFIED')),
				'2' => array('value' => -1,'text' => JText::_('JS_NOT_VERIFIED')),);
		//$paymentstatus = $this->getPaymentStatus(' ');


	   if ($searchtitle) $lists['searchtitle'] = $searchtitle;
	   if ($searchprice) $lists['searchprice'] = $searchprice;

	   if ($searchpaymentstatus)
				$lists['paymentstatus'] = JHTML::_('select.genericList', $paymentstatus, 'searchpaymentstatus', 'class="inputbox" '.'onChange="document.adminForm.submit();"', 'value', 'text', $searchpaymentstatus);
			else
				$lists['paymentstatus'] = JHTML::_('select.genericList', $paymentstatus, 'searchpaymentstatus', 'class="inputbox" '.'onChange="document.adminForm.submit();"', 'value', 'text', '');


		$result[0] = $this->_application;
		$result[1] = $total;
		$result[2]= $lists;
		return $result;
	}

	function & getEmployerPaymentHistorybyId($c_id)
	{
		if (is_numeric($c_id) == false) return false;
		$db = & JFactory :: getDBO();


		$query = "SELECT payment.*,package.companiesallow,package.jobsallow,package.featuredcompaines,package.goldcompanies,package.featuredjobs,
				package.goldjobs,package.resumesearch,package.saveresumesearch,package.viewresumeindetails,package.video,package.map,package.featuredcompaniesexpireindays,
				package.goldcompaniesexpireindays,package.featuredjobsexpireindays,package.goldjobsexpireindays,package.shortdetails,package.description,
				package.featuredcompaniesexpireindays,package.goldcompaniesexpireindays,company.name AS companyname,user.name AS employername,
				package.featuredjobsexpireindays,package.goldjobsexpireindays,package.price,package.discount,package.discountstartdate,package.discountenddate,
				package.enforcestoppublishjob,package.enforcestoppublishjobvalue,package.enforcestoppublishjobtype,package.packageexpireindays
				FROM #__wrecruit_employerpaymenthistory AS payment
				JOIN #__wrecruit_employerpackages AS package ON payment.packageid = package.id
				LEFT JOIN #__wrecruit_companies AS company ON company.id = payment.companyid
				JOIN #__users AS user ON user.id = payment.uid ";
				$query .="WHERE  payment.id=".$c_id;
				//echo $query;
		$db->setQuery($query);
		$package = $db->loadObject();


		$result[0]=$package;


		return $result;

	}


	function & getJobseekerPaymentHistorybyId($c_id)
	{
		if (is_numeric($c_id) == false) return false;
		$db = & JFactory :: getDBO();
		$query = "SELECT payment.*,package.resumeallow,package.coverlettersallow,package.featuredresume,package.goldresume,package.jobsearch,
				package.savejobsearch,package.applyjobs,package.freaturedresumeexpireindays,package.goldresumeexpireindays,package.video,
				package.shortdetails,package.description,package.price,package.discount,package.discountstartdate,package.discountenddate,
				package.packageexpireindays,company.name AS companyname,user.name AS jobseekername
				FROM #__wrecruit_jobseekerpaymenthistory AS payment
				JOIN #__wrecruit_jobseekerpackages AS package ON payment.packageid = package.id
				LEFT JOIN #__wrecruit_companies AS company ON company.uid = payment.uid
				JOIN #__users AS user ON user.id = payment.uid  ";
				$query .=" WHERE payment.id=".$c_id;
				//echo $query ;
		$db->setQuery($query);
		$package = $db->loadObject();

		$result[0]=$package;

		return $result;

	}


// Payment Package End

// For Combo Start
	function getCompany( $title ){
                $db =& JFactory::getDBO();
                $query = "SELECT id, name FROM ".$db->nameQuote('#__wrecruit_companies')." WHERE status = 1 ORDER BY id ASC ";
                $db->setQuery( $query );
                $rows = $db->loadObjectList();
                if ($db->getErrorNum()) {
                        echo $db->stderr();
                        return false;
                }
                $companies = array();
                if($title)
                        $companies[] =  array('value' => '','text' => $title);

                foreach($rows as $row)	{
                        $companies[] =  array('value' => $row->id,	'text' => $row->name);
                }
            return $companies;
	}

	function getEmployerPackageForCombo( $title ){
			$db =& JFactory::getDBO();
			$query = "SELECT id, title FROM ".$db->nameQuote('#__wrecruit_employerpackages')." WHERE status = 1 ORDER BY id ASC ";
			$db->setQuery( $query );
			$rows = $db->loadObjectList();
			if ($db->getErrorNum()) {
				echo $db->stderr();
				return false;
			}
			$packages = array();
			if($title)
				$packages[] =  array('value' => '','text' => $title);

			foreach($rows as $row)	{
				$packages[] =  array('value' => $row->id,	'text' => $row->title);
			}
		return $packages;	
	}

        function getFreeEmployerPackageForCombo( $title ){
			$db =& JFactory::getDBO();
			$query = "SELECT id, title FROM ".$db->nameQuote('#__wrecruit_employerpackages')." WHERE status = 1 AND price = 0 ORDER BY id ASC ";
			$db->setQuery( $query );
			$rows = $db->loadObjectList();
			if ($db->getErrorNum()) {
				echo $db->stderr();
				return false;
			}
			$packages = array();
			if($title)
				$packages[] =  array('value' => '','text' => $title);

			foreach($rows as $row)	{
				$packages[] =  array('value' => $row->id,	'text' => $row->title);
			}
		return $packages;
	}
	
	function getJobSeekerPackageForCombo( $title ){
			$db =& JFactory::getDBO();
			$query = "SELECT id, title FROM ".$db->nameQuote('#__wrecruit_jobseekerpackages')." WHERE status = 1 ORDER BY id ASC ";
			$db->setQuery( $query );
			$rows = $db->loadObjectList();
			if ($db->getErrorNum()) {
				echo $db->stderr();
				return false;
			}
			$packages = array();
			if($title)
				$packages[] =  array('value' => '','text' => $title);

			foreach($rows as $row)	{
				$packages[] =  array('value' => $row->id,	'text' => $row->title);
			}
		return $packages;	
	}
		
	function getFreeJobSeekerPackageForCombo( $title ){
			$db =& JFactory::getDBO();
			$query = "SELECT id, title FROM ".$db->nameQuote('#__wrecruit_jobseekerpackages')." WHERE status = 1 AND price = 0 ORDER BY id ASC ";
			$db->setQuery( $query );
			$rows = $db->loadObjectList();
			if ($db->getErrorNum()) {
				echo $db->stderr();
				return false;
			}
			$packages = array();
			if($title)
				$packages[] =  array('value' => '','text' => $title);

			foreach($rows as $row)	{
				$packages[] =  array('value' => $row->id,	'text' => $row->title);
			}
		return $packages;
	}

        function getJobType( $title ){
//		if ( !$this->_jobtype){
			$db =& JFactory::getDBO();
			$query = "SELECT id, title FROM ".$db->nameQuote('#__wrecruit_jobtypes')." WHERE isactive = 1 ORDER BY id ASC ";
			$db->setQuery( $query );
			$rows = $db->loadObjectList();
			if ($db->getErrorNum()) {
				echo $db->stderr();
				return false;
			}
			$this->_jobtype = array();
			if($title)
				$this->_jobtype[] =  array('value' => JText::_(''),'text' => $title);

			foreach($rows as $row)
			{
				$this->_jobtype[] =  array('value' => JText::_($row->id),
								'text' => JText::_($row->title));
			}

//		}
		return $this->_jobtype;
	}

	function getJobStatus( $title ){
//		if ( !$this->_jobstatus){
			$db =& JFactory::getDBO();
			$query = "SELECT id, title FROM ".$db->nameQuote('#__wrecruit_jobstatus')." WHERE isactive = 1 ORDER BY id ASC ";
			$db->setQuery( $query );
			$rows = $db->loadObjectList();
			if ($db->getErrorNum()) {
				echo $db->stderr();
				return false;
			}
			$this->_jobstatus = array();
			if($title)
				$this->_jobstatus[] =  array('value' => JText::_(''),'text' => $title);

			foreach($rows as $row)	{
				$this->_jobstatus[] =  array('value' => JText::_($row->id),	'text' => JText::_($row->title));
			}
//		}
		return $this->_jobstatus;
	}

	function getHeighestEducation( $title ){
//		if ( !$this->_heighesteducation ){
			$db =& JFactory::getDBO();
			$query = "SELECT id, title FROM ".$db->nameQuote('#__wrecruit_heighesteducation')." WHERE isactive = 1 ORDER BY id ASC ";
			$db->setQuery( $query );
			$rows = $db->loadObjectList();
			if ($db->getErrorNum()) {
				echo $db->stderr();
				return false;
			}
			$this->_heighesteducation = array();
			if($title)
				$this->_heighesteducation[] =  array('value' => JText::_(''),'text' => $title);

			foreach($rows as $row)	{
				$this->_heighesteducation[] =  array('value' => JText::_($row->id),	'text' => JText::_($row->title));
			}
//		}
		return $this->_heighesteducation;
	}


	function getShift( $title ){
		if ( !$this->_shifts ){
			$db =& JFactory::getDBO();
			$query = "SELECT id, title FROM ".$db->nameQuote('#__wrecruit_shifts')." WHERE isactive = 1 ORDER BY id ASC ";
			$db->setQuery( $query );
			$rows = $db->loadObjectList();
			if ($db->getErrorNum()) {
				echo $db->stderr();
				return false;
			}
			$this->_shifts = array();
			if($title)
				$this->_shifts[] =  array('value' => JText::_(''),'text' => $title);
			foreach($rows as $row)	{
				$this->_shifts[] =  array('value' => JText::_($row->id),	'text' => JText::_($row->title));
			}
		}
		return $this->_shifts;
	}
	function getRoles( $rolefor ){
		$db =& JFactory::getDBO();

		if ($rolefor != "")
			$query = "SELECT id, title FROM ".$db->nameQuote('#__wrecruit_roles')." WHERE rolefor = ". $rolefor ." AND published = 1 ORDER BY id ASC ";
		else
			$query = "SELECT id, title FROM ".$db->nameQuote('#__wrecruit_roles')." WHERE published = 1 ORDER BY id ASC ";

		$db->setQuery( $query );
		$rows = $db->loadObjectList();
		if ($db->getErrorNum()) {
			echo $db->stderr();
			return false;
		}
		$roles = array();
		foreach($rows as $row)	{
			$roles[] =  array('value' => $row->id,	'text' => $row->title);
		}
		return $roles;
	}
	
	
	function getSalaryRangeTypes( $title ){
		$db =& JFactory::getDBO();
		$query = "SELECT id, title FROM ".$db->nameQuote('#__wrecruit_salaryrangetypes')." WHERE status = 1 ORDER BY id ASC ";
		$db->setQuery( $query );
		$rows = $db->loadObjectList();
		if ($db->getErrorNum()) {
			echo $db->stderr();
			return false;
		}
		$types = array();
		if($title)
			$types[] =  array('value' => JText::_(''),'text' => $title);
		foreach($rows as $row)	{
			$types[] =  array('value' => $row->id,	'text' => $row->title);
		}
		return $types;	
	}

	function getRequiredTravel($title){
		$requiredtravel = array();
		if ($title)
			$requiredtravel[] = array('value' => '','text' => $title);
		$requiredtravel[] = array('value' => 1,'text' => JText::_('JS_NOT_REQUIRED'));
		$requiredtravel[] = array('value' => 2,'text' => JText::_('JS_25_PER'));
		$requiredtravel[] = array('value' => 3,'text' => JText::_('JS_50_PER'));
		$requiredtravel[] = array('value' => 4,'text' => JText::_('JS_75_PER'));
		$requiredtravel[] = array('value' => 5,'text' => JText::_('JS_100_PER'));
		return $requiredtravel;
	}
	function getMiniMax( $title ){
		$minimax = array();
		if($title)
			$minimax[] =  array('value' => JText::_(''),'text' => $title);
		$minimax[] =  array('value' => 1,'text' => JText::_('JS_MINIMUM'));
		$minimax[] =  array('value' => 2,'text' => JText::_('JS_MAXIMUM'));
		
		return $minimax;	
	}
	function getCareerLevels( $title ){
		if ( !$this->_careerlevels ){
			$db =& JFactory::getDBO();
			$query = "SELECT id, title FROM ".$db->nameQuote('#__wrecruit_careerlevels')." WHERE status = 1 ORDER BY id ASC ";
			$db->setQuery( $query );
			$rows = $db->loadObjectList();
			if ($db->getErrorNum()) {
				echo $db->stderr();
				return false;
			}
			$this->_careerlevels = array();
			if($title)
				$this->_careerlevels[] =  array('value' => JText::_(''),'text' => $title);
			foreach($rows as $row)	{
				$this->_careerlevels[] =  array('value' => $row->id,	'text' => $row->title);
			}
		}						
		return $this->_careerlevels;	
	}

	function getAges( $title ){
		if ( !$this->_ages ){// make problem with age from, age to
			$db =& JFactory::getDBO();
			$query = "SELECT id, title FROM ".$db->nameQuote('#__wrecruit_ages')." WHERE status = 1 ORDER BY id ASC ";
			$db->setQuery( $query );
			$rows = $db->loadObjectList();
			if ($db->getErrorNum()) {
				echo $db->stderr();
				return false;
			}
			$this->_ages = $rows;
		}						
			$ages = array();
			if($title)
				$ages[] =  array('value' => JText::_(''),'text' => $title);
			foreach($this->_ages  as $row)	{
				$ages[] =  array('value' => $row->id,	'text' => $row->title);
			}
		return $ages;	
	}

	function getExperiences( $title ){
		if ( !$this->_experiences ){
			$db =& JFactory::getDBO();
			$query = "SELECT id, title FROM ".$db->nameQuote('#__wrecruit_experiences')." WHERE status = 1 ORDER BY id ASC ";
			$db->setQuery( $query );
			$rows = $db->loadObjectList();
			if ($db->getErrorNum()) {
				echo $db->stderr();
				return false;
			}
			$this->_experiences = $rows;
		}	
			
			$experiences = array();
			if($title)
				$experiences[] =  array('value' => JText::_(''),'text' => $title);
			foreach($this->_experiences as $row)	{
				$experiences[] =  array('value' => $row->id,	'text' => $row->title);
			}
		return $experiences;	
	}
	function getGender($title){
		$gender = array();
		if ($title)
			$gender[] = array('value' => '','text' => $title);
		$gender[] = array('value' => 1,'text' => JText::_('JS_MALE'));
		$gender[] = array('value' => 2,'text' => JText::_('JS_FEMALE'));
		return $gender;
	}
	function getSendEmail(){
		$values = array();
		$values[] = array('value' => 0,'text' => JText::_('JS_NO'));
		$values[] = array('value' => 1,'text' => JText::_('JS_YES'));
		$values[] = array('value' => 2,'text' => JText::_('JS_YES_WITH_RESUME'));
		return $values;
	}

	function getDepartment( $uid )
	{
		if($uid) if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
			$db =& JFactory::getDBO();
			$query = "SELECT id, name FROM ".$db->nameQuote('#__wrecruit_departments')." WHERE uid = ". $uid ." AND status = 1  ORDER BY name ASC ";
			$db->setQuery( $query );
			$rows = $db->loadObjectList();
			if ($db->getErrorNum()) {
				echo $db->stderr();
				return false;
			}
			$departments = array();
			foreach($rows as $row)
			{
				$departments[] =  array('value' => JText::_($row->id),
								'text' => JText::_($row->name));
			}
		return $departments;	
	}
	
// Get Combo End

	
// Ajax Start
	function &listSearchAddressData($data,$val)
	{
		$db = &$this->getDBO();

		if ($data=='country') {  // country
			$query  = "SELECT code, name FROM ".$db->nameQuote('#__wrecruit_countries')." WHERE enabled = 'Y' ORDER BY name ASC";
			$db->setQuery($query);
			$result = $db->loadObjectList();

			if (empty($result))	{
				$return_value = "<input class='inputbox' type='text' name='country' size='40' maxlength='100'  />";
			}else {
				$return_value = "<select name='country' class='inputbox' onChange=\"dochange('state', this.value)\">\n";
				$return_value .= "<option value=''>".JText::_('JS_SEARCH_ALL')."</option>\n";

				foreach($result as $row){
			       $return_value .= "<option value=\"$row->code\" >$row->name</option> \n" ;
				}
				$return_value .= "</select>\n";
			}

		}else if ($data=='state') {  // states
		    $query  = "SELECT code, name from ".$db->nameQuote('#__wrecruit_states')."  WHERE enabled = 'Y' AND countrycode= '$val' ORDER BY name ASC";
			$db->setQuery($query);
			$result = $db->loadObjectList();
			if (empty($result))	{
				$return_value = "<input class='inputbox' type='text' name='state' size='40' maxlength='100'  />";
			}else {
				$return_value = "<select name='state' class='inputbox' onChange=\"dochange('county', this.value)\">\n";
				$return_value .= "<option value=''>".JText::_('JS_SEARCH_ALL')."</option>\n";

				foreach($result as $row){
					   $return_value .= "<option value=\"$row->code\" >$row->name</option> \n" ;
				}
				$return_value .= "</select>\n";
			}
		}else if ($data=='county') {  // county
		    $query  = "SELECT code, name from ".$db->nameQuote('#__wrecruit_counties')."  WHERE enabled = 'Y' AND statecode= '$val' ORDER BY name ASC";
			$db->setQuery($query);
			$result = $db->loadObjectList();

			if (empty($result))	{
				$return_value = "<input class='inputbox' type='text' name='county' size='40' maxlength='100'  />";
			}else
			{
				  $return_value = "<select name='county' class='inputbox' onChange=\"dochange('city', this.value)\">\n";
				  $return_value .= "<option value=''>".JText::_('JS_SEARCH_ALL')."</option>\n";


				  foreach($result as $row){
				       $return_value .= "<option value=\"$row->code\" >$row->name</option> \n" ;
				  }
				$return_value .= "</select>\n";
			}


		} else if ($data=='city') { // city
		    $query  = "SELECT code, name from ".$db->nameQuote('#__wrecruit_cities')."  WHERE enabled = 'Y' AND countycode= '$val' ORDER BY 'name'";
			$db->setQuery($query);
			$result = $db->loadObjectList();
			//if (mysql_num_rows($result)== 0)
			if (empty($result))	{
				$return_value = "<input class='inputbox' type='text' name='city' size='40' maxlength='100'  />";
			}else
			{
				  $return_value = "<select name='city' class='inputbox' onChange=\"dochange('zipcode', this.value)\">\n";
				  $return_value .= "<option value=''>".JText::_('JS_SEARCH_ALL')."</option>\n";


				  foreach($result as $row){
				       $return_value .= "<option value=\"$row->code\" >$row->name</option> \n" ;
				  }
				$return_value .= "</select>\n";
			}

		}
		return $return_value;
	}

	
	function &listDepartments($val)
	{
		$db = &$this->getDBO();
		
		$query  = "SELECT id, name FROM ".$db->nameQuote('#__wrecruit_departments')."  WHERE status = 1 AND companyid = ".$val."
				ORDER BY name ASC";
		$db->setQuery($query);
		$result = $db->loadObjectList();

		if (isset($result)){	
			$return_value = "<select name='departmentid' class='inputbox' >\n";

			foreach($result as $row){
				$return_value .= "<option value=\"$row->id\" >$row->name</option> \n" ;
			}
			$return_value .= "</select>\n";
		}

		return $return_value;
	}
	function &listSubCategories($val)
	{
		$db = &$this->getDBO();

		$query  = "SELECT id, title FROM ".$db->nameQuote('#__wrecruit_subcategories')."  WHERE status = 1 AND categoryid = ".$val." ORDER BY title ASC";
		$db->setQuery($query);
		$result = $db->loadObjectList();

		if (isset($result)){
			$return_value = "<select name='subcategoryid' class='inputbox' >\n";
                                $return_value .= "<option value='' >".JText::_('JS_SUB_CATEGORY')."</option> \n" ;
			foreach($result as $row){
				$return_value .= "<option value=\"$row->id\" >$row->title</option> \n" ;
			}
			$return_value .= "</select>\n";
		}
		return $return_value;
	}
	
// Ajax End
	function loadAddressData()
	{
		$db =& JFactory::getDBO();
		$data = JRequest :: get('post');
		$str=JPATH_BASE;
		$base = substr($str, 0,strlen($str)-14); //remove administrator
		$returncode = 1;
		if ($data['actiontype'] == 1){ // first time
			if($_FILES['loadaddressdata']['size'] > 0){
				$file_name = $_FILES['loadaddressdata']['name']; // file name
				$file_tmp = $_FILES['loadaddressdata']['tmp_name']; // actual location
				$file_size = $_FILES['loadaddressdata']['size']; // file size
				$file_type = $_FILES['loadaddressdata']['type']; // mime type of file determined by php
				$file_error = $_FILES['loadaddressdata']['error']; // any error!. get reason here

				if( !empty($file_tmp)){	// only MS office and text file is accepted.
					$ext = $this->getExtension($file_name);
					if (($ext != "txt") && ($ext != "sql") )
						return 3; //file type mistmathc
				}

				$path =$base.'/components/com_wrecruit/data';
//				echo 'path '.$path;
				if (!file_exists($path)){ // creating data directory
					mkdir($path, 0755);
				}

				$path =$base.'/components/com_wrecruit/data/temp';
//				echo 'path '.$path;
				if (!file_exists($path)){ // creating temp directory
					mkdir($path, 0755);
				}
				$comp_filename = $path.'/' . $file_name;
				move_uploaded_file($file_tmp, $path.'/' . $file_name);
				
				$myFile = $comp_filename;
				
				$fh = fopen($myFile, 'r');
				$theData = fread($fh, filesize($myFile));
				fclose($fh);
//				echo '<br>'.$theData.'<br>';
				
				$start = strpos($theData,'###CTYST',0);
				$end  = strpos($theData,'###CTYED',0); 				
				$start = $start + 9;
//				echo '<br> start '.$start;
//				echo '<br> end '.$end;
				$len  = $end - $start;
				$country = substr($theData,$start,$len);
//				echo '<br> country '.$country;	
				
				$prtstart = strpos($theData,'###PRTST',0);
				$prtend  = strpos($theData,'###PRTED',0); 				
				$prtstart = $prtstart + 9;
//				echo '<br> start '.$prtstart;
//				echo '<br> end '.$prtend;
				$prtlen  = $prtend - $prtstart;
				$prt = substr($theData,$prtstart,$prtlen);
//				echo '<br> prt '.$prt;	

				//if ($country == '' ) return 3;
				if ($prt == 1){
					$query = "SELECT count(id) FROM ".$db->nameQuote('#__wrecruit_country') ." WHERE countrycode = ".$db->Quote($country);
					$db->setQuery( $query );
					$countryresult = $db->loadResult();

					$query = "SELECT count(id) FROM ".$db->nameQuote('#__wrecruit_states') ." WHERE countrycode = ".$db->Quote($country);
					$db->setQuery( $query );
					$stateresult = $db->loadResult();
					if ($stateresult != 0) $returncode = 5;
					
					$query = "SELECT count(id) FROM ".$db->nameQuote('#__wrecruit_counties') ." WHERE countrycode = ".$db->Quote($country);
					$db->setQuery( $query );
					$countyresult = $db->loadResult();
					if ($countyresult != 0){
						if ($returncode != 0) $returncode = 11;
						else $returncode = 7;
					}
					$query = "SELECT count(id) FROM ".$db->nameQuote('#__wrecruit_cities') ." WHERE countrycode = ".$db->Quote($country);
					$db->setQuery( $query );
					$cityresult = $db->loadResult();
					if ($cityresult != 0){
						if ($returncode != 0) $returncode = $returncode + 1;
						else $returncode = 7;
						
					}
				}	
				if($returncode == 1){		
					$db->setQuery($theData);
					if ( $result = $db->queryBatch())
						return 1;
					else{
						return 2;
					}
				}else{
					$_SESSION['js_address_data_filename'] = $myFile;
				}
				/*			
							$handle = fopen($myFile, 'r');
				while (!feof($handle))
				{
				$Data = fgets($handle, 256);
				print $Data;
				print "<p>";


				}
				fclose($handle); 
					$lines = file($myFile);
					foreach ($lines as $line_num => $line)
					{
					print "<font color=red>Line #{$line_num}</font> : " . $line . "<br />\n";
					}
				*/
				return $returncode;
			}
			
		}elseif($data['actiontype'] == 3){ // delete and insert	
			$myFile = $_SESSION['js_address_data_filename'];
			$fh = fopen($myFile, 'r');
			$theData = fread($fh, filesize($myFile));
			fclose($fh);
//			echo '<br>'.$theData.'<br>';

			$start = strpos($theData,'###CTYST',0);
			$end  = strpos($theData,'###CTYED',0); 				
			$start = $start + 9;
			$len  = $end - $start;
			$country = substr($theData,$start,$len);
			
			$countrydata = strpos($theData,'### COUNTRY ###',0);
			$statesdata = strpos($theData,'### STATES ###',0);

			$countiesdata = strpos($theData,'### COUNTIES ###',0);
			$citiesdata = strpos($theData,'### CITIES ###',0);
			
			if ($countrydata != 0){ // country data exist
				$query = "DELETE FROM ".$db->nameQuote('#__wrecruit_country') ." WHERE countrycode = ".$db->Quote($country);
				$db->setQuery( $query );
				$db->query();
			}
			if ($statesdata != 0) { //stats exist
				$query = "DELETE FROM ".$db->nameQuote('#__wrecruit_states') ." WHERE countrycode = ".$db->Quote($country);
				$db->setQuery( $query );
				$db->query();
			}
			if ($countiesdata != 0) { //counties exist
				$query = "DELETE FROM ".$db->nameQuote('#__wrecruit_counties') ." WHERE countrycode = ".$db->Quote($country);
				$db->setQuery( $query );
				$db->query();
			}
			if ($citiesdata != 0) { //citiesexist
				$query = "DELETE FROM ".$db->nameQuote('#__wrecruit_cities') ." WHERE countrycode = ".$db->Quote($country);
				$db->setQuery( $query );
				$db->query();
			}
			$db->setQuery($theData);
			if ( $result = $db->queryBatch())
				return 1;
			else{
				return 2;
			}
	
		}elseif($data['actiontype'] == 4){ // insert	
			$myFile = $_SESSION['js_address_data_filename'];
			$fh = fopen($myFile, 'r');
			$theData = fread($fh, filesize($myFile));
			fclose($fh);
//			echo '<br>'.$theData.'<br>';
			$db->setQuery($theData);
			if ( $result = $db->queryBatch())
				return 1;
			else{
				return 2;
			}
		
		}
		

	}
	
	function isCountryExist($country)
	{
		$db =& JFactory::getDBO();
		$query = "SELECT COUNT(id) FROM #__wrecruit_countries WHERE name = ".$db->Quote($country);
		$db->setQuery( $query );
		$result = $db->loadResult();
		if ($result == 0)
			return false;
		else
			return true;
	}
	function isStateExist($state, $countrycode)
	{
		$db =& JFactory::getDBO();
		$query = "SELECT COUNT(id) FROM #__wrecruit_states WHERE name = ".$db->Quote($state)." AND countrycode = ".$db->Quote($countrycode);
		//echo '<br> SQL '.$query;
		$db->setQuery( $query );
		$result = $db->loadResult();
		if ($result == 0)
			return false;
		else
			return true;
	}
	function isCountyExist($county, $statecode)
	{
		$db =& JFactory::getDBO();
		$query = "SELECT COUNT(id) FROM #__wrecruit_counties WHERE name = ".$db->Quote($county)." AND statecode = ".$db->Quote($statecode);
		//echo '<br> SQL '.$query;
		$db->setQuery( $query );
		$result = $db->loadResult();
		if ($result == 0)
			return false;
		else
			return true;
	}
	function isCityExist($city, $countycode)
	{
		$db =& JFactory::getDBO();
		$query = "SELECT COUNT(id) FROM #__wrecruit_cities WHERE name = ".$db->Quote($city)." AND countycode = ".$db->Quote($countycode);
		$db->setQuery( $query );
		$result = $db->loadResult();
		if ($result == 0)
			return false;
		else
			return true;
	}

	function makeCountryCode($country)
	{
		$db =& JFactory::getDBO();
		$code = substr($country, 0, 2); 
		$found = false;
		$start = 1;
		while (!$found == true){
			$query = "SELECT COUNT(id) FROM #__wrecruit_countries WHERE code = ".$db->Quote($code);
			$db->setQuery( $query );
			$result = $db->loadResult();
			if ($result == 0){
				$found = true;
				return $code;
			}else {
				$code = substr($country, $start, 2); 
				$start++;
				if($start == strlen($country))	return false;	
			}	
		}
	}

	function makeStateCode($stat, $countrycode)
	{
		$db =& JFactory::getDBO();
		$state = str_replace (" ", "", $stat); // remove spaces
		$totallen = strlen($state);
		$len = 4;
		if ($len > $totallen) $len = $totallen;
		$code = substr($state, 0, $len); 
		$found = false;
		$start = 0;
		while (!$found == true){
			$query = "SELECT COUNT(id) FROM #__wrecruit_states WHERE code = ".$db->Quote($code);
			$db->setQuery( $query );
			$result = $db->loadResult();
			if ($result == 0){
				$found = true;
				return $code;
			}else {
				$code = substr($state, 0, $len); 
				if($len == $totallen) $code .= $countrycode;
				if($len > $totallen)	return false;	
				$len++;
			}	
		}
	}

	function makeCountyCode($count, $statecode)
	{
		$db =& JFactory::getDBO();
		$county = str_replace (" ", "", $count); // remove spaces
		$totallen = strlen($county);
		$len = 4;
		if ($len > $totallen) $len = $totallen;
		$code = substr($county, 0, $len); 
		$found = false;
		$start = 0;
		while (!$found == true){
			$query = "SELECT COUNT(id) FROM #__wrecruit_counties WHERE code = ".$db->Quote($code);
			$db->setQuery( $query );
			$result = $db->loadResult();
			if ($result == 0){
				$found = true;
				return $code;
			}else {
				$code = substr($county, 0, $len); 
				if($len == $totallen){
					$county .= $statecode;
					$totallen = strlen($county);
					$code = substr($county, 0, $len); 
				}	
				if($len > $totallen)	return false;	
				$len++;
			}	
		}
	}

	function makeCityCode($cit, $countycode)
	{
		$db =& JFactory::getDBO();
		$city = str_replace (" ", "", $cit); // remove spaces
		$totallen = strlen($city);
		$len = 4;
		if ($len > $totallen) $len = $totallen;
		$code = substr($city, 0, $len); 
		$found = false;
		$start = 0;
		while (!$found == true){
			$query = "SELECT COUNT(id) FROM #__wrecruit_cities WHERE code = ".$db->Quote($code);
			$db->setQuery( $query );
			$result = $db->loadResult();
			if ($result == 0){
				$found = true;
				return $code;
			}else {
				$code = substr($city, 0, $len); 
				if($len == $totallen){
					$city .= $countycode;
					$totallen = strlen($city);
					$code = substr($city, 0, $len); 
				}	
				if($len > $totallen)	return false;	
				$len++;
			}	
		}
	}

	function uploadFile($id, $action, $isdeletefile)
	{
		$db =& JFactory::getDBO();

		$str=JPATH_BASE;
		$base = substr($str, 0,strlen($str)-14); //remove administrator
		//$path =$base.'/components/com_wrecruit/data/employer';
		//echo '<br> path '.$path;
                if(! isset($this->_config)) $this->getConfig();
                foreach ($this->_config as $conf){
                        if ($conf->configname == 'data_directory') $datadirectory = $conf->configvalue;
                }
                $path =$base.'/'.$datadirectory;
		//$path =$base.'/components/com_wrecruit';
		$isupload = false;
		$path= $path . '/data';
		if (!file_exists($path)){ // create user directory
			mkdir($path, 0755);
		}
		$path= $path . '/employer';
		if (!file_exists($path)){ // create user directory
			mkdir($path, 0755);
		}
		
		$isupload = false;
		if ($action == 1) { //Company logo
			if($_FILES['logo']['size'] > 0){
				$file_name = $_FILES['logo']['name']; // file name
				$file_tmp = $_FILES['logo']['tmp_name']; // actual location
				
				$ext = $this->getExtension($file_name);
				$ext = strtolower($ext);
				if (($ext != "gif") && ($ext != "jpg") && ($ext != "jpeg") && ($ext != "png"))
					return 6; //file type mistmathc
					
				$userpath= $path . '/comp_'.$id;
				if (!file_exists($userpath)){ // create user directory
					mkdir($userpath, 0755);
				}
				$userpath= $userpath. '/logo';
				if (!file_exists($userpath)){ // create logo directory
					mkdir($userpath, 0755);
				}
				$isupload = true;
			}
		}elseif ($action == 2) { //Company small logo
			if($_FILES['smalllogo']['size'] > 0){
				$file_name = $_FILES['smalllogo']['name']; // file name
				$file_tmp = $_FILES['smalllogo']['tmp_name']; // actual location
				
				$ext = $this->getExtension($file_name);
				$ext = strtolower($ext);
				if (($ext != "gif") && ($ext != "jpg") && ($ext != "jpeg") && ($ext != "png"))
					return 6; //file type mistmathc
					
				$userpath= $path . '/comp_'.$id;
				if (!file_exists($userpath)){ // create user directory
					mkdir($userpath, 0755);
				}
				$userpath= $userpath. '/smalllogo';
				if (!file_exists($userpath)){ // create logo directory
					mkdir($userpath, 0755);
				}
				$isupload = true;
			}
		}elseif ($action == 3) { //About Company
			if($_FILES['aboutcompany']['size'] > 0){
				$file_name = $_FILES['aboutcompany']['name']; // file name
				$file_tmp = $_FILES['aboutcompany']['tmp_name']; // actual location
				
				$ext = $this->getExtension($file_name);
				$ext = strtolower($ext);
				if (($ext != "txt") && ($ext != "doc") && ($ext != "docx") && ($ext != "pdf"))
					return 6; //file type mistmathc
					
				$userpath= $path . '/comp_'.$id;
				if (!file_exists($userpath)){ // create user directory
					mkdir($userpath, 0755);
				}
				$userpath= $userpath. '/aboutcompany';
				if (!file_exists($userpath)){ // create logo directory
					mkdir($userpath, 0755);
				}
				$isupload = true;
			}
		
		
		}
		
		if ($isupload){
			$files = glob($userpath.'/*.*');
			array_map('unlink', $files);  //delete all file in directory
			
			move_uploaded_file($file_tmp, $userpath.'/' . $file_name);
			//unlink($file_tmp);
			
			return 1;
		}else { // DELETE FILES
			if ($action == 1) { // company logo
				if ($isdeletefile == 1){
					$userpath= $path . '/comp_'.$id . '/logo';
					$files = glob($userpath.'/*.*');
					array_map('unlink', $files); // delete all file in the direcoty 
				}
			}elseif ($action == 2) { // company small logo
				if ($isdeletefile == 1){
					$userpath= $path . '/comp_'.$id . '/smalllogo';
					$files = glob($userpath.'/*.*');
					array_map('unlink', $files); // delete all file in the direcoty 
				}
			}elseif ($action == 3) { // about company 
				if ($isdeletefile == 1){
					$userpath= $path . '/comp_'.$id . '/aboutcompany';
					$files = glob($userpath.'/*.*');
					array_map('unlink', $files); // delete all file in the direcoty 
				}
			}
			return 1;
		}

	}
	function departmentApprove($departmentid)
	{
		if (is_numeric($departmentid) == false) return false;
		$db =& JFactory::getDBO();
		
		$query = "UPDATE #__wrecruit_departments SET status = 1 WHERE id = ".$departmentid;
		//echo '<br>sql '.$query;
		$db->setQuery( $query );
		if (!$db->query()) {
			return false;
		}
		//return $this->sendMail(2, 1, $job_id);
		return true;
	}
	
	function departmentReject($departmentid)
	{
		if (is_numeric($departmentid) == false) return false;
		$db =& JFactory::getDBO();
		
		$query = "UPDATE #__wrecruit_departments SET status = -1 WHERE id = ".$departmentid;
		//echo '<br>sql '.$query;
		$db->setQuery( $query );
		if (!$db->query()) {
			return false;
		}
		//return $this->sendMail(2, 1, $job_id);
		return true;
	}

	
	
	function companyApprove($company_id)
	{
		if (is_numeric($company_id) == false) return false;
		$db =& JFactory::getDBO();

                $query = "UPDATE #__wrecruit_companies SET status = 1 WHERE id = ".$company_id;
		$db->setQuery( $query );
		if (!$db->query()) return false;
		return $this->sendMail(1, 1, $company_id);
	}

	function companyReject($company_id)
	{
		if (is_numeric($company_id) == false) return false;
		$db =& JFactory::getDBO();
		
		$query = "UPDATE #__wrecruit_companies SET status = -1 WHERE id = ".$company_id;
		$db->setQuery( $query );
		if (!$db->query()) {
			return false;
		}
		return $this->sendMail(1, -1, $company_id);
	}

/* zain */
	function folderApprove($folderid)
	{
		if (is_numeric($folderid) == false) return false;
		$db =& JFactory::getDBO();

                $query = "UPDATE #__wrecruit_folders SET status = 1 WHERE id = ".$folderid;
		$db->setQuery( $query );
		if (!$db->query()) return false;
		return $this->sendMail(1, 1, $folderid);
	}

	function folderReject($folderid)
	{
		if (is_numeric($folderid) == false) return false;
		$db =& JFactory::getDBO();

		$query = "UPDATE #__wrecruit_folders SET status = -1 WHERE id = ".$folderid;
		$db->setQuery( $query );
		if (!$db->query()) {
			return false;
		}
		return $this->sendMail(1, -1, $folderid);
	}

	function jobApprove($job_id)
	{
		if (is_numeric($job_id) == false) return false;
		$db =& JFactory::getDBO();
		
		$query = "UPDATE #__wrecruit_jobs SET status = 1 WHERE id = ".$db->Quote($job_id);
		$db->setQuery( $query );
		if (!$db->query()) {
			return false;
		}
		$this->sendMail(2, 1, $job_id);
		//$this->sendJobAlertJobseeker($job_id);
		register_shutdown_function(array($this,'sendJobAlertJobseeker'),$job_id);

		return true;
	}


	function jobReject($job_id)
	{
		if (is_numeric($job_id) == false) return false;
		$db =& JFactory::getDBO();
		
		$query = "UPDATE #__wrecruit_jobs SET status = -1 WHERE id = ".$db->Quote($job_id);
		$db->setQuery( $query );
		if (!$db->query()) {
			return false;
		}
		return $this->sendMail(2, -1, $job_id);
	}

	function empappApprove($app_id)
	{
		if (is_numeric($app_id) == false) return false;
		$db =& JFactory::getDBO();
		
		$query = "UPDATE #__wrecruit_resume SET status = 1 WHERE id = ".$db->Quote($app_id);
		$db->setQuery( $query );
		if (!$db->query()) {
			return false;
		}
		return $this->sendMail(3, 1, $app_id);
	}

	function empappReject($app_id)
	{
		if (is_numeric($app_id) == false) return false;
		$db =& JFactory::getDBO();
		
		$query = "UPDATE #__wrecruit_resume SET status = -1 WHERE id = ".$db->Quote($app_id);
		$db->setQuery( $query );
		if (!$db->query()) {
			return false;
		}
		return $this->sendMail(3, -1, $app_id);
	}

	function fieldPublished($field_id, $value)
	{
		if (is_numeric($field_id) == false) return false;
		$db =& JFactory::getDBO();
		
		$query = " UPDATE #__wrecruit_fieldsordering
					SET published = ". $value ."
					WHERE id = ". $field_id ;
		//echo '<br>sql '.$query;
		$db->setQuery( $query );
		if (!$db->query()) {
			return false;
		}
		return true;
	}

	function fieldOrderingUp($field_id)
	{
		if (is_numeric($field_id) == false) return false;
		$db =& JFactory::getDBO();
		
		$query = "UPDATE #__wrecruit_fieldsordering AS f1, #__wrecruit_fieldsordering AS f2
					SET f1.ordering = f1.ordering - 1
					WHERE f1.ordering = f2.ordering + 1
					AND f1.fieldfor = f2.fieldfor
					AND f2.id = ". $field_id ." ; " ;
		$db->setQuery( $query );
		if (!$db->query()) {return false;	}
		
		$query = " UPDATE #__wrecruit_fieldsordering
					SET ordering = ordering + 1
					WHERE id = ". $field_id .";"
					;
		//echo '<br>sql '.$query;
		$db->setQuery( $query );
		if (!$db->query()) {
			return false;
		}
		return true;
	}

	function fieldOrderingDown($field_id)
	{
		if (is_numeric($field_id) == false) return false;
		$db =& JFactory::getDBO();
		
		$query = "UPDATE jos_wrecruit_fieldsordering AS f1, jos_wrecruit_fieldsordering AS f2
					SET f1.ordering = f1.ordering + 1
					WHERE f1.ordering = f2.ordering - 1
					AND f1.fieldfor = f2.fieldfor
					AND f2.id = ". $field_id ." ; ";

		$db->setQuery( $query );
		if (!$db->query()) {return false;	}
		
		$query = " UPDATE #__wrecruit_fieldsordering
					SET ordering = ordering - 1
					WHERE id = ". $field_id .";"	;
		//echo '<br>sql '.$query;
		$db->setQuery( $query );
		if (!$db->query()) {
			return false;
		}
		return true;
	}

	function &listAddressData($data,$val)
	{
		$db = &$this->getDBO();
		
		if ($data=='country') {  // country
			$query  = "SELECT code, name FROM ".$db->nameQuote('#__wrecruit_countries')."  WHERE enabled = 'Y' ORDER BY name ASC";
			$db->setQuery($query);
			$result = $db->loadObjectList();

			if (empty($result))	{
				$return_value = "<input class='inputbox' type='text' name='country' size='40' maxlength='100'  />";
			}else {
				$return_value = "<select name='country' onChange=\"dochange('state', this.value)\">\n";
				$return_value .= "<option value='0'>". JText::_('JS_CHOOSE_COUNTRY') ."</option>\n";

				foreach($result as $row){
			       $return_value .= "<option value=\"$row->code\" >$row->name</option> \n" ;
				}
				$return_value .= "</select>\n";
			}

		}else if ($data=='state') {  // states
		    $query  = "SELECT code, name from ".$db->nameQuote('#__wrecruit_states')."  WHERE enabled = 'Y' AND countrycode= '$val' ORDER BY name ASC";
			$db->setQuery($query);
			$result = $db->loadObjectList();
			if (empty($result))	{
				$return_value = "<input class='inputbox' type='text' name='state' size='40' maxlength='100'  />";
			}else {
				$return_value = "<select name='state' class='inputbox' onChange=\"dochange('county', this.value)\">\n";
				$return_value .= "<option value='0'>". JText::_('JS_CHOOSE_STATE') ."</option>\n";

				foreach($result as $row){
					   $return_value .= "<option value=\"$row->code\" >$row->name</option> \n" ;
				}
				$return_value .= "</select>\n";
			}
		}else if ($data=='county') {  // county
		    $query  = "SELECT code, name from ".$db->nameQuote('#__wrecruit_counties')."  WHERE enabled = 'Y' AND statecode= '$val' ORDER BY name ASC";
			$db->setQuery($query);
			$result = $db->loadObjectList();

			if (empty($result))
			{

				$return_value = "<input class='inputbox' type='text' name='county' size='40' maxlength='100'  />";
			}else
			{
				  $return_value = "<select name='county' class='inputbox' onChange=\"dochange('city', this.value)\">\n";
				  $return_value .= "<option value='0'>". JText::_('JS_CHOOSE_COUNTY') ."</option>\n";
				  
				  
				  foreach($result as $row){
				       $return_value .= "<option value=\"$row->code\" >$row->name</option> \n" ;
				  }
				$return_value .= "</select>\n";
			}


		} else if ($data=='city') { // city
		    $query  = "SELECT code, name from ".$db->nameQuote('#__wrecruit_cities')."  WHERE enabled = 'Y' AND countycode= '$val' ORDER BY 'name'";
			$db->setQuery($query);
			$result = $db->loadObjectList();
			//if (mysql_num_rows($result)== 0)
			if (empty($result))
			{
				$return_value = "<input class='inputbox' type='text' name='city' size='40' maxlength='100'  />";
			}else
			{
				  $return_value = "<select name='city' class='inputbox' onChange=\"dochange('zipcode', this.value)\">\n";
				  $return_value .= "<option value='0'>". JText::_('JS_CHOOSE_CITY') ."</option>\n";
				  
				  
				  foreach($result as $row){
				       $return_value .= "<option value=\"$row->code\" >$row->name</option> \n" ;
				  }
				$return_value .= "</select>\n";
			}

		}
		return $return_value;
	}

	function &listEmpAddressData($name, $myname, $nextname, $data, $val)
	{
		$db = &$this->getDBO();

		
		if ($data=='country') {  // country
			$query  = "SELECT code, name FROM ".$db->nameQuote('#__wrecruit_countries')."  WHERE enabled = 'Y' ORDER BY name ASC";
			$db->setQuery($query);
			$result = $db->loadObjectList();

			if (empty($result))	{
				$return_value = "<input class='inputbox' type='text' name='$name' size='40' maxlength='100'  />";
			}else {

				$return_value = "<select name='$name' onChange=\"dochange(\"$myname\",'state', this.value)\">\n";
				$return_value .= "<option value='0'>". JText::_('JS_CHOOSE_COUNTRY') ."</option>\n";

				foreach($result as $row){
				   $return_value .= "<option value=\"$row->code\" >$row->name</option> \n" ;
				}
				$return_value .= "</select>\n";
			}

		}else if ($data=='state') {  // states
		    $query  = "SELECT code, name from ".$db->nameQuote('#__wrecruit_states')."  WHERE enabled = 'Y' AND countrycode= '$val' ORDER BY name ASC";
			$db->setQuery($query);
			$result = $db->loadObjectList();
			if (empty($result))	{
				$return_value = "<input class='inputbox' type='text' name='$name' size='40' maxlength='100'  />";
			}else
			{
				$return_value = "<select name='$name' class='inputbox' onChange=\"dochange('$myname','$nextname','','county', this.value)\">\n";
				$return_value .= "<option value='0'>". JText::_('JS_CHOOSE_STATE') ."</option>\n";
				  
				foreach($result as $row){
					   $return_value .= "<option value=\"$row->code\" >$row->name</option> \n" ;
				  }
				$return_value .= "</select>\n";
			}
		}else if ($data=='county') {  // county
		    $query  = "SELECT code, name from ".$db->nameQuote('#__wrecruit_counties')."  WHERE enabled = 'Y' AND statecode= '$val' ORDER BY name ASC";
			$db->setQuery($query);
			$result = $db->loadObjectList();

			if (empty($result))	{
				$return_value = "<input class='inputbox' type='text' name='$name' size='40' maxlength='100'  />";
			}else
			{
				$return_value = "<select name='$name' class='inputbox' onChange=\"dochange('$myname','','','city', this.value)\">\n";
				$return_value .= "<option value='0'>". JText::_('JS_CHOOSE_COUNTY') ."</option>\n";
				  
				foreach($result as $row){
					   $return_value .= "<option value=\"$row->code\" >$row->name</option> \n" ;
				  }
				$return_value .= "</select>\n";
			}


		} else if ($data=='city') { // second dropdown
		    $query  = "SELECT code, name from ".$db->nameQuote('#__wrecruit_cities')."  WHERE enabled = 'Y' AND countycode= '$val' ORDER BY 'name'";
			$db->setQuery($query);
			$result = $db->loadObjectList();
			if (empty($result))	{
				$return_value = "<input class='inputbox' type='text' name='$name' size='40' maxlength='100'  />";
			}else
			{
				$return_value = "<select name='$name' class='inputbox' onChange=\"dochange('zipcode', this.value)\">\n";
				$return_value .= "<option value='0'>". JText::_('JS_CHOOSE_CITY') ."</option>\n";
				  
				foreach($result as $row){
				    $return_value .= "<option value=\"$row->code\" >$row->name</option> \n" ;
				}
				$return_value .= "</select>\n";
			}

		}
		return $return_value;
	}		

	function & getApplication()
	{
		if (!$this->_application && $this->_id != null)
		{
			$db = & $this->getDBO();
			$query = "SELECT * FROM " . $db->nameQuote('#__wrecruit_jobs') . " WHERE " .
			$db->nameQuote('id') . " = " . $this->_id;
			$db->setQuery($query);
			$this->_application = $db->loadObject();
			$this->getOptions();
		}
		return $this->_application;
	}

	// save the current data
	function save($data)
	{
	}

	// increment the hit counter <<---- not used
	
	function & getUid()
	{
	}
	

	function isCategoryExist($cat_title)
	{
		$db =& JFactory::getDBO();
		
		$query = "SELECT COUNT(id) FROM #__wrecruit_categories WHERE cat_title = ".$db->Quote($cat_title);
		//echo '<br>sql '.$query;
		$db->setQuery( $query );
		$result = $db->loadResult();
		//echo '<br>r'.$result;
		if ($result == 0)
			return false;
		else
			return true;
			
	}
	function isSubCategoryExist($title)
	{
		$db =& JFactory::getDBO();

		$query = "SELECT COUNT(id) FROM #__wrecruit_subcategories WHERE title = ".$db->Quote($title);
		//echo '<br>sql '.$query;
		$db->setQuery( $query );
		$result = $db->loadResult();
		if ($result == 0) return false;
		else return true;
	}

	function SalaryRangeValidation($rangestart, $rangeend)
	{
		$db =& JFactory::getDBO();
		
		$query = "SELECT COUNT(id) FROM #__wrecruit_categories WHERE cat_title = ".$db->Quote($cat_title);
		//echo '<br>sql '.$query;
		$db->setQuery( $query );
		$result = $db->loadResult();
		//echo '<br>r'.$result;
		if ($result == 0)
			return false;
		else
			return true;
			
	}
	//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
	//send mail
	function &sendMail($for, $action, $id)
	{
		//action			1 = job approved, 2 = job reject 6, resume approved, 7 resume reject
		$db =& JFactory::getDBO();
		$str = JURI::base();
		if (strtolower(substr($str, strlen($str)-14, 13)) == "administrator")		
			$siteAddress = substr($str, 0,strlen($str)-14); //remove administrator
		else
			$siteAddress = $str;
			

		if ($for == 1 ){ //company
			if ($action == 1){ // company approved
				$templatefor = 'company-approval';
			}elseif ($action == -1){ //company reject
				$templatefor = 'company-rejecting';
			}
		}elseif ($for == 2 ){ //job
			if ($action == 1){ // job approved
				$templatefor = 'job-approval';
			}elseif ($action == -1){ // job reject
				$templatefor = 'job-rejecting';
			}
		}elseif ($for == 3 ){ // resume
			if ($action == 1){ //resume approved
				$templatefor = 'resume-approval';
			}elseif ($action == -1){ // resume reject
				$templatefor = 'resume-rejecting';
			}
		}
		
		$query = "SELECT template.* FROM ".$db->nameQuote('#__wrecruit_emailtemplates') ."AS template	WHERE template.templatefor = ".$db->Quote($templatefor);
		$db->setQuery( $query );
		$template = $db->loadObject();
		$msgSubject = $template->subject;
		$msgBody = $template->body;

		if ($for == 1 ){ //company
			$query = "SELECT company.name, company.contactname, company.contactemail FROM ".$db->nameQuote('#__wrecruit_companies') ."AS company
				WHERE company.id = ".$id;
			//echo '<br>sql '.$query;	

			$db->setQuery( $query );
			$company = $db->loadObject();

			$Name=$company->contactname;
			$Email=$company->contactemail;
			$companyName=$company->name;
			
			$msgSubject = str_replace('{COMPANY_NAME}', $companyName, $msgSubject);
			$msgSubject = str_replace('{EMPLOYER_NAME}', $Name, $msgSubject);
			$msgBody = str_replace('{COMPANY_NAME}', $companyName, $msgBody);
			$msgBody = str_replace('{EMPLOYER_NAME}', $Name, $msgBody);
/*
			if ($action == 1){ // company approved
				$msgSubject = " Your Company $companyTitle has been approved";
				$msgBody="Dear  $Name , \n\n Your company <b>$companyTitle</b> has been approved.\n Login and view detail at $siteAddress  \n\nPlease do not respond to this message. It is automatically generated and is for information purposes only.";
			}elseif ($action == -1){ //company reject
				$msgSubject = "Your company $companyTitle has been rejected";
				$msgBody="Dear  $Name , \n\n Your company <b>$companyTitle</b> has been rejected.\n Login and view detail at $siteAddress  \n\nPlease do not respond to this message. It is automatically generated and is for information purposes only.";
			}
*/
		}elseif ($for == 2 ){ //job
			$query = "SELECT job.title, company.contactname, company.contactemail 
						FROM ".$db->nameQuote('#__wrecruit_jobs') ."AS job
						JOIN ".$db->nameQuote('#__wrecruit_companies') ."AS company ON job.companyid = company.id
				WHERE job.id = ".$id;
			//echo '<br>sql '.$query;	
			$db->setQuery( $query );
			$job = $db->loadObject();

			$Name=$job->contactname;
			$Email=$job->contactemail;
			$jobTitle=$job->title;
			$msgSubject = str_replace('{JOB_TITLE}', $jobTitle, $msgSubject);
			$msgSubject = str_replace('{EMPLOYER_NAME}', $Name, $msgSubject);
			$msgBody = str_replace('{JOB_TITLE}', $jobTitle, $msgBody);
			$msgBody = str_replace('{EMPLOYER_NAME}', $Name, $msgBody);			
/*			
			if ($action == 1){ // job approved
				$msgSubject = " Your job $jobTitle has been approved";
				$msgBody="Dear  $Name , \n\n Your job <b>$jobTitle</b> has been approved.\n Login and view detail at $siteAddress  \n\nPlease do not respond to this message. It is automatically generated and is for information purposes only.";
			}elseif ($action == -1){ // job reject
				$msgSubject = "Your job $jobTitle has been rejected";
				$msgBody="Dear  $Name , \n\n Your job <b>$jobTitle</b> has been rejected.\n Login and view detail at $siteAddress  \n\nPlease do not respond to this message. It is automatically generated and is for information purposes only.";
			}
*/
		}elseif ($for == 3 ){ // resume
			$query = "SELECT app.application_title, app.first_name, app.middle_name, app.last_name, app.email_address FROM ".$db->nameQuote('#__wrecruit_resume') ."AS app
				WHERE app.id = ".$id;
				
			//echo '<br>sql '.$query;		
			$db->setQuery( $query );
			$app = $db->loadObject();
			
			$Name=$app->first_name;
			if ($app->middle_name) $Name .= " ".$app->middle_name;
			if ($app->last_name) $Name .= " ".$app->last_name;
			$Email=$app->email_address;
			$resumeTitle=$app->application_title;
			$msgSubject = str_replace('{RESUME_TITLE}', $resumeTitle, $msgSubject);
			$msgSubject = str_replace('{JOBSEEKER_NAME}', $Name, $msgSubject);
			$msgBody = str_replace('{RESUME_TITLE}', $resumeTitle, $msgBody);
			$msgBody = str_replace('{JOBSEEKER_NAME}', $Name, $msgBody);			
/*
			if ($action == 1){ //resume approved
				$msgSubject = "Your resume $jobTitle has been approved";
				$msgBody="Dear  $Name , \n\n Your resume <b>$jobTitle</b> has been approved.\n Login and view detail at $siteAddress  \n\nPlease do not respond to this message. It is automatically generated and is for information purposes only.";
			}elseif ($action == -1){ // resume reject
				$msgSubject = "Your resume $jobTitle has been rejected";
				$msgBody="Dear  $Name , \n\n Your resume <b>$jobTitle</b> has been rejected.\n Login and view detail at $siteAddress  \n\nPlease do not respond to this message. It is automatically generated and is for information purposes only.";
			}
*/		
		}

			if ( !$this->_config )
				$this->getConfig();
			foreach ($this->_config as $conf){
				if ($conf->configname == 'mailfromname')
					$senderName = $conf->configvalue;
				if ($conf->configname == 'mailfromaddress')
					$senderEmail = $conf->configvalue;
			}

			$message =& JFactory::getMailer();
			$message->addRecipient($Email); //to email

			$message->setSubject($msgSubject);
			$message->setBody($msgBody);
			$sender = array( $senderEmail, $senderName );
			$message->setSender($sender);
			$message->IsHTML(true);
			$sent = $message->send();
		
			
			return true;
			//			return $sent;
			//if ($sent != 1) echo 'Error sending email';
 	}
        function sendJobAlertJobseeker($jobid){
            $db = &$this->getDBO();
			if ((is_numeric($jobid) == false) || ($jobid == 0) || ($jobid == '')) return false;
            $query = "SELECT job.title,job.jobcategory, category.cat_title AS categorytitle, subcategory.title AS subcategorytitle
                            ,subcategory.id AS subcategoryid, job.country, job.state, job.county, job.city
                            , country.name as countryname, state.name as statename, county.name as countyname, city.name as cityname

                        FROM ".$db->nameQuote('#__wrecruit_jobs')." AS job
                        JOIN ".$db->nameQuote('#__wrecruit_categories')." AS category ON job.jobcategory  = category.id
                        LEFT JOIN ".$db->nameQuote('#__wrecruit_subcategories')." AS subcategory ON job.subcategoryid = subcategory.categoryid
                         JOIN ".$db->nameQuote('#__wrecruit_countries')." AS country ON job.country = country.code
                        LEFT JOIN ".$db->nameQuote('#__wrecruit_states')." AS state ON job.state = state.code
                        LEFT JOIN ".$db->nameQuote('#__wrecruit_counties')." AS county ON job.county = county.code
                        LEFT JOIN ".$db->nameQuote('#__wrecruit_cities')." AS city ON job.city = city.code
                        WHERE job.id = ".$jobid;
            //echo '<br>'.$query;
            $db->setQuery($query);
            $job = $db->loadObject();
            $countryquery = "(SELECT jobalert.contactemail
                            FROM ".$db->nameQuote('#__wrecruit_jobalertsetting')." AS jobalert
                            WHERE jobalert.categoryid = ".$job->jobcategory." 
							AND LOWER(jobalert.country) = LOWER(".$db->quote($job->country) .")";
                if($job->subcategoryid) $countryquery .= " AND jobalert.subcategoryid = ".$db->quote($job->subcategoryid);
                if($job->state) $countryquery .= " AND LOWER(jobalert.state) != LOWER(".$db->quote($job->state).")";
                if($job->county) $countryquery .= " AND LOWER(jobalert.county) != LOWER(".$db->quote($job->county).")";
                if($job->city) $countryquery .= " AND LOWER(jobalert.city) != LOWER(".$db->quote($job->city).")";
            $countryquery .= ")";
            $query = $countryquery;
            if($job->state){
                $statequery = "(SELECT jobalert.contactemail
                                FROM ".$db->nameQuote('#__wrecruit_jobalertsetting')." AS jobalert
                                WHERE jobalert.categoryid = ".$job->jobcategory." 
								AND LOWER(jobalert.country) = LOWER(".$db->quote($job->country) .")";
					if($job->subcategoryid) $statequery .= " AND jobalert.subcategoryid = ".$db->quote($job->subcategoryid);
                    if($job->state) $statequery .= " AND LOWER(jobalert.state) = LOWER(".$db->quote($job->state).")";
                    if($job->county) $statequery .= " AND LOWER(jobalert.county) != LOWER(".$db->quote($job->county).")";
                    if($job->city) $statequery .= " AND LOWER(jobalert.city) != LOWER(".$db->quote($job->city).")";
                $statequery .= ")";
               $query .= " UNION " . $statequery;
            }
            if($job->county){
                $countyquery = "(SELECT jobalert.contactemail
                                FROM ".$db->nameQuote('#__wrecruit_jobalertsetting')." AS jobalert
                                WHERE jobalert.categoryid = ".$job->jobcategory." 
								AND LOWER(jobalert.country) = LOWER(".$db->quote($job->country) .")";
					if($job->subcategoryid) $countyquery .= " AND jobalert.subcategoryid = ".$db->quote($job->subcategoryid);
                    if($job->state) $countyquery .= " AND LOWER(jobalert.state) = LOWER(".$db->quote($job->state).")";
                    if($job->county) $countyquery .= " AND LOWER(jobalert.county) = LOWER(".$db->quote($job->county).")";
                    if($job->city) $countyquery .= " AND LOWER(jobalert.city) != LOWER(".$db->quote($job->city).")";
                $countyquery .= ")";
               $query .= " UNION " . $countyquery;
            }
            if($job->city){
                $cityquery = "(SELECT jobalert.contactemail
                                FROM ".$db->nameQuote('#__wrecruit_jobalertsetting')." AS jobalert
                                WHERE jobalert.categoryid = ".$job->jobcategory." 
								AND LOWER(jobalert.country) = LOWER(".$db->quote($job->country) .")";
					if($job->subcategoryid) $cityquery .= " AND jobalert.subcategoryid = ".$db->quote($job->subcategoryid);
                    if($job->state) $cityquery .= " AND LOWER(jobalert.state) = LOWER(".$db->quote($job->state).")";
                    if($job->county) $cityquery .= " AND LOWER(jobalert.county) = LOWER(".$db->quote($job->county).")";
                    if($job->city) $cityquery .= " AND LOWER(jobalert.city) = LOWER(".$db->quote($job->city).")";
                $cityquery .= ")";
               $query .= " UNION " . $cityquery;
            }
            //echo '<br>'.$query;
            $db->setQuery($query);
            $result = $db->loadObjectList();
			
			if (isset($result)){
	            foreach ($result AS $email){
	                $bcc[] = $email->contactemail;
	                echo '<br>'.$email->contactemail;
	            }
			}else exit;
			
            $comma = '';
            if($job->cityname) {$location = $comma.$job->cityname; $comma = ', ';}
            elseif($job->city) {$location = $comma.$job->city; $comma = ', ';}
            if($job->countyname) {$location = $comma.$job->countyname; $comma = ', ';}
            elseif($job->county) {$location = $comma.$job->county; $comma = ', ';}
            if($job->statename) {$location = $comma.$job->statename; $comma = ', ';}
            elseif($job->state) {$location = $comma.$job->state; $comma = ', ';}
            $location .= $comma.$job->countryname;
            $msgSubject = 'New Job';
            $query = "SELECT template.* FROM ".$db->nameQuote('#__wrecruit_emailtemplates') ."AS template	WHERE template.templatefor = 'job-alert'";
            $db->setQuery( $query );
            $template = $db->loadObject();
            $msgSubject = $template->subject;
            $msgBody = $template->body;

            $msgBody = str_replace('{JOB_TITLE}', $job->title, $msgBody);
            $msgBody = str_replace('{CATEGORY}', $job->categorytitle, $msgBody);
            $msgBody = str_replace('{SUB_CATEGORY}', $job->subcategorytitle, $msgBody);
            $msgBody = str_replace('{LOCATION}', $location, $msgBody);

			$config = $this->getConfigByFor('email');

            $message =& JFactory::getMailer();
            $message->addRecipient($config['mailfromaddress']); //to email
            
            //$message->addCC($cc);
            $message->addBCC($bcc);

            $message->setSubject($msgSubject);
            $message->setBody($msgBody);
            $sender = array( $config['mailfromaddress'], $config['mailfromname']);
            $message->setSender($sender);

            $message->IsHTML(true);
            //print_r($bcc) ;
            //echo '<br>'.$msgBody;
            $sent = $message->send();
			//echo '<br>Error sending email: ' . $sent->message;
            return $result;
        }
	//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
		function &getEmpOptions()
	{
		if ( !$this->_empoptions )
		{
			$this->_empoptions = array();

		$gender = array(
			'0' => array('value' => 1,'text' => JText::_('JS_MALE')),
			'1' => array('value' => 2,'text' => JText::_('JS_FEMALE')),);

		$status = array(
			'0' => array('value' => 0,'text' => JText::_('JS_PENDDING')),
			'1' => array('value' => 1,'text' => JText::_('JS_APPROVE')),
			'2' => array('value' => -1,'text' => JText::_('JS_REJECT')),);
		
			$job_type = $this->getJobType('');
			$heighesteducation = $this->getHeighestEducation('');
			$job_categories = $this->getCategories('','');
			$job_salaryrange = $this->getJobSalaryRange('','');
			$countries = $this->getCountries('');

			if(isset($this->_application))$address_states = $this->getStates($this->_application->address_country);
			if(isset($this->_application))$address_counties = $this->getCounties($this->_application->address_state);
			if(isset($this->_application))$address_cities = $this->getCities($this->_application->address_county);

			if(isset($this->_application))$institute_states = $this->getStates($this->_application->institute_country);
			if(isset($this->_application))$institute_counties = $this->getCounties($this->_application->institute_state);
			if(isset($this->_application))$institute_cities = $this->getCities($this->_application->institute_county);
			
			if(isset($this->_application))$institute1_states = $this->getStates($this->_application->institute1_country);
			if(isset($this->_application))$institute1_counties = $this->getCounties($this->_application->institute1_state);
			if(isset($this->_application))$institute1_cities = $this->getCities($this->_application->institute1_county);

			if(isset($this->_application))$employer_states = $this->getStates($this->_application->employer_country);
			if(isset($this->_application))$employer_counties = $this->getCounties($this->_application->employer_state);
			if(isset($this->_application))$employer_cities = $this->getCities($this->_application->employer_county);
			
			if ( isset($this->_application) )
			{
				$this->_empoptions['nationality'] = JHTML::_('select.genericList', $countries, 'nationality','class="inputbox" '.'', 'value', 'text', $this->_application->nationality);
				$this->_empoptions['gender'] = JHTML::_('select.genericList', $gender, 'gender','class="inputbox" '.'', 'value', 'text', $this->_application->gender);

				$this->_empoptions['job_category'] = JHTML::_('select.genericList', $job_categories, 'job_category', 'class="inputbox" '. '', 'value', 'text', $this->_application->job_category);

				$this->_empoptions['address_country'] = JHTML::_('select.genericList', $countries, 'address_country','class="inputbox" '.'onChange="dochange(\'address_state\', \'address_county\',\'address_city\', \'state\', this.value)"', 'value', 'text', $this->_application->address_country);
				if (isset($address_states[1])) if ($address_states[1] != '')$this->_empoptions['address_state'] = JHTML::_('select.genericList', $address_states, 'address_state', 'class="inputbox" '. 'onChange="dochange(\'address_county\, \'address_city\', , this.value)"', 'value', 'text', $this->_application->address_state);
				if (isset($address_counties[1])) if ($address_counties[1] != '')$this->_empoptions['address_county'] = JHTML::_('select.genericList', $address_counties, 'address_county', 'class="inputbox" '. 'onChange="dochange(\'address_city\, , , this.value)"', 'value', 'text', $this->_application->address_county);
				if (isset($address_cities[1])) if ($address_cities[1] != '')$this->_empoptions['address_city'] = JHTML::_('select.genericList', $address_cities, 'address_city', 'class="inputbox" '. '', 'value', 'text', $this->_application->address_city);
				
				$this->_empoptions['address1_country'] = JHTML::_('select.genericList', $countries, 'address1_country','class="inputbox" '.'onChange="dochange(\'address1_state\', \'address1_county\',\'address1_city\',\'state\', this.value)"', 'value', 'text', $this->_application->address1_country);
				$this->_empoptions['address2_country'] = JHTML::_('select.genericList', $countries, 'address2_country','class="inputbox" '.'onChange="dochange(\'address2_state\', \'address2_county\',\'address2_city\',\'state\', this.value)"', 'value', 'text', $this->_application->address2_country);

				$this->_empoptions['institute_country'] = JHTML::_('select.genericList', $countries, 'institute_country','class="inputbox" '.'onChange="dochange(\'institute_state\', \'institute_county\',\'institute_city\', \'state\', this.value)"', 'value', 'text', $this->_application->institute_country);
				if (isset($institute_states[1])) if ($institute_states[1] != '')$this->_empoptions['institute_state'] = JHTML::_('select.genericList', $institute_states, 'institute_state', 'class="inputbox" '. 'onChange="dochange(\'institute_county\, \'institute_city\', , this.value)"', 'value', 'text', $this->_application->institute_state);
				if (isset($institute_counties[1])) if ($institute_counties[1] != '')$this->_empoptions['institute_county'] = JHTML::_('select.genericList', $institute_counties, 'institute_county', 'class="inputbox" '. 'onChange="dochange(\'institute_city\,  , , this.value)"', 'value', 'text', $this->_application->institute_county);
				if (isset($institute_cities[1])) if ($institute_cities[1] != '')$this->_empoptions['institute_city'] = JHTML::_('select.genericList', $institute_cities, 'institute_city', 'class="inputbox" '. '', 'value', 'text', $this->_application->institute_city);

				$this->_empoptions['institute1_country'] = JHTML::_('select.genericList', $countries, 'institute1_country','class="inputbox" '.'onChange="dochange(\'institute1_state\', \'institute1_county\',\'institute1_city\',\'state\', this.value)"', 'value', 'text', $this->_application->institute1_country);
				if (isset($institute1_states[1])) if ($institute1_states[1] != '')$this->_empoptions['institute1_state'] = JHTML::_('select.genericList', $institute1_states, 'institute1_state', 'class="inputbox" '. 'onChange="dochange(\'institute1_county\, \'institute1_city\', , this.value)"', 'value', 'text', $this->_application->institute1_state);
				if (isset($institute1_counties[1])) if ($institute1_counties[1] != '')$this->_empoptions['institute1_county'] = JHTML::_('select.genericList', $institute1_counties, 'institute1_county', 'class="inputbox" '. 'onChange="dochange(\'institute1_city\,  , , this.value)"', 'value', 'text', $this->_application->institute1_county);
				if (isset($institute1_cities[1])) if ($institute1_cities[1] != '')$this->_empoptions['institute1_city'] = JHTML::_('select.genericList', $institute1_cities, 'institute1_city', 'class="inputbox" '. '', 'value', 'text', $this->_application->institute1_city);

				$this->_empoptions['institute2_country'] = JHTML::_('select.genericList', $countries, 'institute2_country','class="inputbox" '.'onChange="dochange(\'institute2_state\', \'institute2_county\',\'institute2_city\',\'state\', this.value)"', 'value', 'text', $this->_application->institute2_country);
				$this->_empoptions['institute3_country'] = JHTML::_('select.genericList', $countries, 'institute3_country','class="inputbox" '.'onChange="dochange(\'institute3_state\', \'institute3_county\',\'institute3_city\',\'state\', this.value)"', 'value', 'text', $this->_application->institute3_country);

				$this->_empoptions['employer_country'] = JHTML::_('select.genericList', $countries, 'employer_country','class="inputbox" '.'onChange="dochange(\'employer_state\', \'employer_county\',\'employer_city\',\'state\', this.value)"', 'value', 'text', $this->_application->employer_country);
				if (isset($employer_states[1])) if ($employer_states[1] != '')$this->_empoptions['employer_state'] = JHTML::_('select.genericList', $employer_states, 'employer_state', 'class="inputbox" '. 'onChange="dochange(\'employer_county\, \'employer_city\', , this.value)"', 'value', 'text', $this->_application->employer_state);
				if (isset($employer_counties[1])) if ($employer_counties[1] != '')$this->_empoptions['employer_county'] = JHTML::_('select.genericList', $employer_counties, 'employer_county', 'class="inputbox" '. 'onChange="dochange(\'employer_city\,  , , this.value)"', 'value', 'text', $this->_application->employer_county);
				if (isset($employer_cities[1])) if ($employer_cities[1] != '')$this->_empoptions['employer_city'] = JHTML::_('select.genericList', $employer_cities, 'employer_city', 'class="inputbox" '. '', 'value', 'text', $this->_application->employer_city);

				$this->_empoptions['employer1_country'] = JHTML::_('select.genericList', $countries, 'employer1_country','class="inputbox" '.'onChange="dochange(\'employer1_state\', \'employer1_county\',\'employer1_city\',\'state\', this.value)"', 'value', 'text', $this->_application->employer1_country);
				$this->_empoptions['employer2_country'] = JHTML::_('select.genericList', $countries, 'employer2_country','class="inputbox" '.'onChange="dochange(\'employer2_state\', \'employer2_county\',\'employer2_city\',\'state\', this.value)"', 'value', 'text', $this->_application->employer2_country);
				$this->_empoptions['employer3_country'] = JHTML::_('select.genericList', $countries, 'employer3_country','class="inputbox" '.'onChange="dochange(\'employer3_state\', \'employer3_county\',\'employer3_city\',\'state\', this.value)"', 'value', 'text', $this->_application->employer3_country);

				$this->_empoptions['reference_country'] = JHTML::_('select.genericList', $countries, 'reference_country','class="inputbox" '.'onChange="dochange(\'reference_state\', \'reference_county\',\'reference_city\',\'state\', this.value)"', 'value', 'text', $this->_application->reference_country);
				$this->_empoptions['reference1_country'] = JHTML::_('select.genericList', $countries, 'reference1_country','class="inputbox" '.'onChange="dochange(\'reference1_state\', \'reference1_county\',\'reference1_city\',\'state\', this.value)"', 'value', 'text', $this->_application->reference1_country);
				$this->_empoptions['reference2_country'] = JHTML::_('select.genericList', $countries, 'reference2_country','class="inputbox" '.'onChange="dochange(\'reference2_state\', \'reference2_county\',\'reference2_city\',\'state\', this.value)"', 'value', 'text', $this->_application->reference2_country);
				$this->_empoptions['reference3_country'] = JHTML::_('select.genericList', $countries, 'reference3_country','class="inputbox" '.'onChange="dochange(\'reference3_state\', \'reference3_county\',\'reference3_city\',\'state\', this.value)"', 'value', 'text', $this->_application->reference3_country);

				$this->_empoptions['jobtype'] = JHTML::_('select.genericList', $job_type, 'jobtype', 'class="inputbox" '. '', 'value', 'text', $this->_application->jobtype);
				$this->_empoptions['heighestfinisheducation'] = JHTML::_('select.genericList', $heighesteducation, 'heighestfinisheducation', 'class="inputbox" '. '', 'value', 'text', $this->_application->heighestfinisheducation);
				$this->_empoptions['jobsalaryrange'] = JHTML::_('select.genericList', $job_salaryrange, 'jobsalaryrange', 'class="inputbox" '. '', 'value', 'text', $this->_application->jobsalaryrange);
				$this->_empoptions['status'] = JHTML::_('select.genericList', $status, 'status', 'class="inputbox required" '. '', 'value', 'text', $this->_application->status);
				$this->_empoptions['currencyid'] = JHTML::_('select.genericList', $this->getCurrency(), 'currencyid', 'class="inputbox required" '. '', 'value', 'text', $this->_application->currencyid);


			}
			else
			{
				$this->_empoptions['nationality'] = JHTML::_('select.genericList', $countries, 'nationality','class="inputbox" '.'', 'value', 'text', '');
				$this->_empoptions['gender'] = JHTML::_('select.genericList', $gender, 'gender','class="inputbox" '.'', 'value', 'text', '');

				$this->_empoptions['job_category'] = JHTML::_('select.genericList', $job_categories, 'job_category', 'class="inputbox" '. '', 'value', 'text', '');
				
				$this->_empoptions['address_country'] = JHTML::_('select.genericList', $countries, 'address_country','class="inputbox" '.'onChange="dochange(\'address_state\', \'address_county\',\'address_city\', \'state\', this.value)"', 'value', 'text', '');
				//echo '<br> st '.$address_states[1];
				if ( isset($address_states[1]) )if ($address_states[1] != '')$this->_empoptions['address_state'] = JHTML::_('select.genericList', $address_states, 'address_state', 'class="inputbox" '. 'onChange="dochange(\'address_county\, \'address_city\', , this.value)"', 'value', 'text', '');
				if ( isset($address_counties[1]) )if ($address_counties[1] != '')$this->_empoptions['address_county'] = JHTML::_('select.genericList', $address_counties, 'address_county', 'class="inputbox" '. 'onChange="dochange(\'address_city\, , , this.value)"', 'value', 'text', '');
				if ( isset($address_cities[1]) )if ($address_cities[1] != '')$this->_empoptions['address_city'] = JHTML::_('select.genericList', $address_cities, 'address_city', 'class="inputbox" '. '', 'value', 'text', '');
				
				$this->_empoptions['address1_country'] = JHTML::_('select.genericList', $countries, 'address1_country','class="inputbox" '.'onChange="dochange(\'address1_state\', \'address1_county\',\'address1_city\',\'state\', this.value)"', 'value', 'text', $this->_application->address1_country);
				$this->_empoptions['address2_country'] = JHTML::_('select.genericList', $countries, 'address2_country','class="inputbox" '.'onChange="dochange(\'address2_state\', \'address2_county\',\'address2_city\',\'state\', this.value)"', 'value', 'text', $this->_application->address2_country);

				$this->_empoptions['institute_country'] = JHTML::_('select.genericList', $countries, 'institute_country','class="inputbox" '.'onChange="dochange(\'institute_state\', \'institute_county\',\'institute_city\', \'state\', this.value)"', 'value', 'text', '');
				if ( isset($institute_states[1]) )if ($institute_states[1] != '')$this->_empoptions['institute_state'] = JHTML::_('select.genericList', $institute_states, 'institute_state', 'class="inputbox" '. 'onChange="dochange(\'institute_county\, \'institute_city\', , this.value)"', 'value', 'text', '');
				if ( isset($institute_counties[1]) )if ($institute_counties[1] != '')$this->_empoptions['institute_county'] = JHTML::_('select.genericList', $institute_counties, 'institute_county', 'class="inputbox" '. 'onChange="dochange(\'institute_city\,  , , this.value)"', 'value', 'text', '');
				if ( isset($institute_cities[1]) )if ($institute_cities[1] != '')$this->_empoptions['institute_city'] = JHTML::_('select.genericList', $institute_cities, 'institute_city', 'class="inputbox" '. '', 'value', 'text', '');

				$this->_empoptions['institute1_country'] = JHTML::_('select.genericList', $countries, 'institute1_country','class="inputbox" '.'onChange="dochange(\'institute1_state\', \'institute1_county\',\'institute1_city\',\'state\', this.value)"', 'value', 'text', '');
				if ($institute1_states[1] != '')$this->_empoptions['institute1_state'] = JHTML::_('select.genericList', $institute1_states, 'institute1_state', 'class="inputbox" '. 'onChange="dochange(\'institute1_county\, \'institute1_city\', , this.value)"', 'value', 'text', '');
				if ($institute1_counties[1] != '')$this->_empoptions['institute1_county'] = JHTML::_('select.genericList', $institute1_counties, 'institute1_county', 'class="inputbox" '. 'onChange="dochange(\'institute1_city\,  , , this.value)"', 'value', 'text', '');
				if ($institute1_cities[1] != '')$this->_empoptions['institute1_city'] = JHTML::_('select.genericList', $institute1_cities, 'institute1_city', 'class="inputbox" '. '', 'value', 'text', '');

				$this->_empoptions['institute2_country'] = JHTML::_('select.genericList', $countries, 'institute2_country','class="inputbox" '.'onChange="dochange(\'institute2_state\', \'institute2_county\',\'institute2_city\',\'state\', this.value)"', 'value', 'text', '');
				$this->_empoptions['institute3_country'] = JHTML::_('select.genericList', $countries, 'institute3_country','class="inputbox" '.'onChange="dochange(\'institute3_state\', \'institute3_county\',\'institute3_city\',\'state\', this.value)"', 'value', 'text', '');

				$this->_empoptions['employer_country'] = JHTML::_('select.genericList', $countries, 'employer_country','class="inputbox" '.'onChange="dochange(\'employer_state\', \'employer_county\',\'employer_city\',\'state\', this.value)"', 'value', 'text', '');
				if ( isset($employer_states[1]) )if ($employer_states[1] != '')$this->_empoptions['employer_state'] = JHTML::_('select.genericList', $employer_states, 'employer_state', 'class="inputbox" '. 'onChange="dochange(\'employer_county\, \'employer_city\', , this.value)"', 'value', 'text', '');
				if ( isset($employer_counties[1]) )if ($employer_counties[1] != '')$this->_empoptions['employer_county'] = JHTML::_('select.genericList', $employer_counties, 'employer_county', 'class="inputbox" '. 'onChange="dochange(\'employer_city\,  , , this.value)"', 'value', 'text', '');
				if ( isset($employer_cities[1]) )if ($employer_cities[1] != '')$this->_empoptions['employer_city'] = JHTML::_('select.genericList', $employer_cities, 'employer_city', 'class="inputbox" '. '', 'value', 'text', '');

				$this->_empoptions['employer1_country'] = JHTML::_('select.genericList', $countries, 'employer1_country','class="inputbox" '.'onChange="dochange(\'employer1_state\', \'employer1_county\',\'employer1_city\',\'state\', this.value)"', 'value', 'text', '');
				$this->_empoptions['employer2_country'] = JHTML::_('select.genericList', $countries, 'employer2_country','class="inputbox" '.'onChange="dochange(\'employer2_state\', \'employer2_county\',\'employer2_city\',\'state\', this.value)"', 'value', 'text', '');
				$this->_empoptions['employer3_country'] = JHTML::_('select.genericList', $countries, 'employer3_country','class="inputbox" '.'onChange="dochange(\'employer3_state\', \'employer3_county\',\'employer3_city\',\'state\', this.value)"', 'value', 'text', '');

				$this->_empoptions['reference_country'] = JHTML::_('select.genericList', $countries, 'reference_country','class="inputbox" '.'onChange="dochange(\'reference_state\', \'reference_county\',\'reference_city\',\'state\', this.value)"', 'value', 'text', '');
				$this->_empoptions['reference1_country'] = JHTML::_('select.genericList', $countries, 'reference1_country','class="inputbox" '.'onChange="dochange(\'reference1_state\', \'reference1_county\',\'reference1_city\',\'state\', this.value)"', 'value', 'text', '');
				$this->_empoptions['reference2_country'] = JHTML::_('select.genericList', $countries, 'reference2_country','class="inputbox" '.'onChange="dochange(\'reference2_state\', \'reference2_county\',\'reference2_city\',\'state\', this.value)"', 'value', 'text', '');
				$this->_empoptions['reference3_country'] = JHTML::_('select.genericList', $countries, 'reference3_country','class="inputbox" '.'onChange="dochange(\'reference3_state\', \'reference3_county\',\'reference3_city\',\'state\', this.value)"', 'value', 'text', '');


				$this->_empoptions['jobtype'] = JHTML::_('select.genericList', $job_type, 'jobtype', 'class="inputbox" '. '', 'value', 'text', '');
				$this->_empoptions['heighestfinisheducation'] = JHTML::_('select.genericList', $heighesteducation, 'heighestfinisheducation', 'class="inputbox" '. '', 'value', 'text', '');
				$this->_empoptions['jobsalaryrange'] = JHTML::_('select.genericList', $job_salaryrange, 'jobsalaryrange', 'class="inputbox" '. '', 'value', 'text', '');
				$this->_empoptions['status'] = JHTML::_('select.genericList', $status, 'status', 'class="inputbox required" '. '', 'value', 'text', '');
				$this->_empoptions['currencyid'] = JHTML::_('select.genericList',$this->getCurrency(), 'currencyid', 'class="inputbox required" '. '', 'value', 'text', '');
			}
		}
		return $this->_empoptions;
	}	
	

	
	// load the options for our templates
	function &getOptions()
	{
		if ( !$this->_options )
		{
			$this->_options = array();
			$job_type = array(
				'0' => array('value' => JText::_(1),
								'text' => JText::_('JS_JOBTYPE_FULLTIME')),
				'1' => array('value' => JText::_(2),
								'text' => JText::_('JS_JOBTYPE_PARTTIME')),
				'3' => array('value' => JText::_(3),
								'text' => JText::_('JS_JOBTYPE_INTERNSHIP')),);
		

			$heighesteducation = array(
				'0' => array('value' => JText::_(1),
								'text' => JText::_('JS_JOBEDUCATION_UNIVERSITY')),
				'1' => array('value' => JText::_(2),
								'text' => JText::_('JS_JOBEDUCATION_COLLEGE')),
				'2' => array('value' => JText::_(2),
								'text' => JText::_('JS_JOBEDUCATION_HIGH_SCHOOL')),
				'3' => array('value' => JText::_(3),
								'text' => JText::_('JS_JOBEDUCATION_NO_SCHOOL')),);

			$jobstatus = array(
				'0' => array('value' => JText::_(1),
								'text' => JText::_('JS_JOBSTATUS_SOURCING')),
				'1' => array('value' => JText::_(2),
								'text' => JText::_('JS_JOBSTATUS_INTERVIEWING')),
				'2' => array('value' => JText::_(3),
								'text' => JText::_('JS_JOBSTATUS_CLOSED')),
				'3' => array('value' => JText::_(4),
								'text' => JText::_('JS_JOBSTATUS_FINALISTS')),
				'4' => array('value' => JText::_(5),
								'text' => JText::_('JS_JOBSTATUS_PENDING')),
				'5' => array('value' => JText::_(6),
								'text' => JText::_('JS_JOBSTATUS_HOLD')),);
								
			
			$job_categories = $this->getCategories('','');
			$job_salaryrange = $this->getJobSalaryRange('','');
			$countries = $this->getCountries('');
			if (isset($this->_application))$states = $this->getStates($this->_application->country);
			if (isset($this->_application))$counties = $this->getCounties($this->_application->state);
			if (isset($this->_application))$cities = $this->getCities($this->_application->county);
			if (isset($this->_application)){
				$this->_options['jobcategory'] = JHTML::_('select.genericList', $job_categories, 'jobcategory', 'class="inputbox" '. '', 'value', 'text', $this->_application->jobcategory);
				$this->_options['jobsalaryrange'] = JHTML::_('select.genericList', $job_salaryrange, 'jobsalaryrange', 'class="inputbox" '. '', 'value', 'text', $this->_application->jobsalaryrange);
				$this->_options['country'] = JHTML::_('select.genericList', $countries, 'country','class="inputbox" '.'onChange="dochange(\'state\', this.value)"', 'value', 'text', $this->_application->country);
				if ( isset($states[1]) ) if ($states[1] != '')$this->_options['state'] = JHTML::_('select.genericList', $states, 'state', 'class="inputbox" '. 'onChange="dochange(\'county\', this.value)"', 'value', 'text', $this->_application->state);
				if ( isset($counties[1]) ) if ($counties[1] != '')$this->_options['county'] = JHTML::_('select.genericList', $counties, 'county', 'class="inputbox" '. 'onChange="dochange(\'city\', this.value)"', 'value', 'text', $this->_application->county);
				if ( isset($cities[1]) ) if ($cities[1] != '')$this->_options['city'] = JHTML::_('select.genericList', $cities, 'city', 'class="inputbox" '. '', 'value', 'text', $this->_application->city);
				$this->_options['jobstatus'] = JHTML::_('select.genericList', $jobstatus, 'jobstatus', 'class="inputbox" '. '', 'value', 'text', $this->_application->jobstatus);				
				$this->_options['jobtype'] = JHTML::_('select.genericList', $job_type, 'jobtype', 'class="inputbox" '. '', 'value', 'text', $this->_application->jobtype);
				$this->_options['heighestfinisheducation'] = JHTML::_('select.genericList', $heighesteducation, 'heighestfinisheducation', 'class="inputbox" '. '', 'value', 'text', $this->_application->heighestfinisheducation);
			}else{
				$this->_options['jobcategory'] = JHTML::_('select.genericList', $job_categories, 'jobcategory', 'class="inputbox" '. '', 'value', 'text', '');
				$this->_options['jobsalaryrange'] = JHTML::_('select.genericList', $job_salaryrange, 'jobsalaryrange', 'class="inputbox" '. '', 'value', 'text', '');
				$this->_options['country'] = JHTML::_('select.genericList', $countries, 'country','class="inputbox" '.'onChange="dochange(\'state\', this.value)"', 'value', 'text', '');
				if ( isset($states[1]) ) if ($states[1] != '')$this->_options['state'] = JHTML::_('select.genericList', $states, 'state', 'class="inputbox" '. 'onChange="dochange(\'county\', this.value)"', 'value', 'text', '');
				if ( isset($counties[1]) ) if ($counties[1] != '')$this->_options['county'] = JHTML::_('select.genericList', $counties, 'county', 'class="inputbox" '. 'onChange="dochange(\'city\', this.value)"', 'value', 'text', '');
				if ( isset($cities[1]) ) if ($cities[1] != '')$this->_options['city'] = JHTML::_('select.genericList', $cities, 'city', 'class="inputbox" '. '', 'value', 'text', '');
				$this->_options['jobstatus'] = JHTML::_('select.genericList', $jobstatus, 'jobstatus', 'class="inputbox" '. '', 'value', 'text', '');				
				$this->_options['jobtype'] = JHTML::_('select.genericList', $job_type, 'jobtype', 'class="inputbox" '. '', 'value', 'text', '');
				$this->_options['heighestfinisheducation'] = JHTML::_('select.genericList', $heighesteducation, 'heighestfinisheducation', 'class="inputbox" '. '', 'value', 'text', '');
			}
		}
		return $this->_options;
	}
	
	function getCategories($title, $value  )
	{
		$db =& JFactory::getDBO();
		
		$query = "SELECT id, cat_title FROM ".$db->nameQuote('#__wrecruit_categories')." WHERE isactive = 1 ORDER BY cat_title ";
//		echo '<br>sql '.$query;
		$db->setQuery( $query );
		$rows = $db->loadObjectList();
		if ($db->getErrorNum()) {
			echo $db->stderr();
			return false;
		}
		$jobcategories = array();
		if ($title) 
			$jobcategories[] =  array('value' => JText::_($value),	'text' => JText::_($title));
		foreach($rows as $row)
		{
		$jobcategories[] =  array('value' => JText::_($row->id),
							'text' => JText::_($row->cat_title));
		}
		return $jobcategories;	
			
	}
	function getSubCategoriesforCombo($categoryid, $title, $value  ){
		$db =& JFactory::getDBO();

		$query = "SELECT id, title FROM ".$db->nameQuote('#__wrecruit_subcategories')." WHERE status = 1 AND categoryid = ".$categoryid." ORDER BY title ";
		$db->setQuery( $query );
		$rows = $db->loadObjectList();
		if ($db->getErrorNum()) {
			echo $db->stderr();
			return false;
		}
		$subcategories = array();
		if ($title) $subcategories[] =  array('value' => JText::_($value),	'text' => JText::_($title));
                foreach($rows as $row){
                    $subcategories[] =  array('value' => $row->id, 'text' => JText::_($row->title));
		}
		return $subcategories;
	}
	function getSalaryRange( $title )
	{
		$db =& JFactory::getDBO();
		if ( !$this->_jobsalaryrange ){		
			$query = "SELECT * FROM ".$db->nameQuote('#__wrecruit_salaryrange')." ORDER BY 'id' ";
			//echo '<br>sql '.$query;
			$db->setQuery( $query );
			$rows = $db->loadObjectList();
			if ($db->getErrorNum()) {
				echo $db->stderr();
				return false;
			}
			$this->_jobsalaryrange = $rows;
		}
		
		if ( !$this->_config )
			$this->getConfig('');
		foreach ($this->_config as $conf){
			if ($conf->configname == 'currency')
				$currency = $conf->configvalue;
		}

		$jobsalaryrange = array();
		if($title)
			$jobsalaryrange[] =  array('value' => JText::_(''),'text' => $title);

		foreach($this->_jobsalaryrange as $row)
		{
			/*			
			$salrange = $currency . $row->rangestart.' - '.$currency . $row->rangeend;
			$salrange = $currency . $row->rangestart;//.' - '.$currency . $row->rangeend;
			*/
			$salrange =  $row->rangestart.' - ' . $row->rangeend;
			$salrange =  $row->rangestart;//.' - '.$currency . $row->rangeend;
			
			
			$jobsalaryrange[] =  array('value' => $row->id,	'text' => $salrange);
		}
		return $jobsalaryrange;	
			
	}


	function getJobSalaryRange($title, $value)
	{
		$db =& JFactory::getDBO();
		
		$query = "SELECT * FROM ".$db->nameQuote('#__wrecruit_salaryrange')." ORDER BY 'id' ";
//		echo '<br>sql '.$query;
		$db->setQuery( $query );
		$rows = $db->loadObjectList();
		if ($db->getErrorNum()) {
			echo $db->stderr();
			return false;
		}
		if ( !$this->_config )
			$this->getConfig();
		foreach ($this->_config as $conf){
			if ($conf->configname == 'currency')
				$currency = $conf->configvalue;
		}
		$jobsalaryrange = array();
		if ($title) 
			$jobsalaryrange[] =  array('value' => JText::_($value),	'text' => JText::_($title));
		foreach($rows as $row)
		{	
			//$salrange = $currency . $row->rangestart.' - '.$currency . $row->rangeend;
			$salrange =  $row->rangestart.' - ' . $row->rangeend;
			$jobsalaryrange[] =  array('value' => JText::_($row->id),
								'text' => JText::_($salrange));
		}
		return $jobsalaryrange;	
			
	}

	function getCountries( $title )
	{
		$db =& JFactory::getDBO();
		$query = "SELECT * FROM ".$db->nameQuote('#__wrecruit_countries')." WHERE enabled = 'Y' ORDER BY name ASC ";
		$db->setQuery( $query );
		$rows = $db->loadObjectList();
		if ($db->getErrorNum()) {
			echo $db->stderr();
			return false;
		}
		$countries = array();
		if ($title) $countries[] =  array('value' => JText::_(''),'text' => $title);
		else $countries[] =  array('value' => JText::_(''),'text' => JText::_('==== choose country ===='));
		foreach($rows as $row)
		{
			$countries[] =  array('value' => JText::_($row->code),
							'text' => JText::_($row->name));
			//echo 'c'.$row->name;
		}
		return $countries;	
	}

	function getStates( $country )
	{
		$states = array();
			$db =& JFactory::getDBO();
			$query = "SELECT * FROM ".$db->nameQuote('#__wrecruit_states')." WHERE enabled = 'Y' AND countrycode = '". $country ."' ORDER BY name ASC ";
			$db->setQuery( $query );
			$rows = $db->loadObjectList();
			if ($db->getErrorNum()) {
				echo $db->stderr();
				return false;
			}
			
			foreach($rows as $row)	{
				$states[] =  array('value' => JText::_($row->code),	'text' => JText::_($row->name));
			}
		return $states;	
	}
	function getCounties( $state )
	{
		$counties = array();
			$db =& JFactory::getDBO();
			$query = "SELECT * FROM ".$db->nameQuote('#__wrecruit_counties')." WHERE enabled = 'Y' AND statecode = '". $state ."' ORDER BY name ASC ";
			$db->setQuery( $query );
			$rows = $db->loadObjectList();
			if ($db->getErrorNum()) {
				echo $db->stderr();
				return false;
			}
			
			foreach($rows as $row)	{
				$counties[] =  array('value' => JText::_($row->code),'text' => JText::_($row->name));
			}
		
		return $counties;	
	}
	function getCities( $county )
	{
		$cities = array();
			$db =& JFactory::getDBO();
			$query = "SELECT * FROM ".$db->nameQuote('#__wrecruit_cities')." WHERE enabled = 'Y' AND countycode = '". $county ."' ORDER BY name ASC ";
			$db->setQuery( $query );
			$rows = $db->loadObjectList();
			if ($db->getErrorNum()) {
				echo $db->stderr();
				return false;
			}
			
			foreach($rows as $row){
				$cities[] =  array('value' => JText::_($row->code),	'text' => JText::_($row->name));
			}
		
		return $cities;	
	}

	function getCompanies( $uid )
	{
		if($uid) if ((is_numeric($uid) == false) || ($uid == 0) || ($uid == '')) return false;
                $db =& JFactory::getDBO();
                $query = "SELECT id, name FROM ".$db->nameQuote('#__wrecruit_companies')." WHERE uid = ". $uid ." AND status = 1 ORDER BY name ASC ";
                $db->setQuery( $query );
                $rows = $db->loadObjectList();
                if ($db->getErrorNum()) {
                        echo $db->stderr();
                        return false;
                }
                $companies = array();
                foreach($rows as $row)
                {
                        $companies[] =  array('value' => JText::_($row->id),
                                                        'text' => JText::_($row->name));
                }
            return $companies;
	}
	
	function getCompaniesbyJobId( $jobid )
	{
		if (is_numeric($jobid) == false) return false;
                $db =& JFactory::getDBO();
                $query = "SELECT company.id, company.name
                FROM ".$db->nameQuote('#__wrecruit_companies')." AS company
                JOIN ".$db->nameQuote('#__wrecruit_jobs')." AS job ON company.uid = job.uid
                WHERE job.id = ". $jobid ." ORDER BY name ASC ";
                $db->setQuery( $query );
                $rows = $db->loadObjectList();
                if ($db->getErrorNum()) {
                        echo $db->stderr();
                        return false;
                }
                $companies = array();
                foreach($rows as $row)
                {
                        $companies[] =  array('value' => JText::_($row->id),
                                                        'text' => JText::_($row->name));
                }
		return $companies;	
	}
	
	function &getConfigByFor($configfor)
	{
			$db = &$this->getDBO();

				$query = "SELECT * FROM ".$db->nameQuote('#__wrecruit_config').' WHERE configfor = '.$db->quote($configfor);
				//echo '<br> SQL '.$query;
				$db->setQuery($query);
				$config = $db->loadObjectList();
				$configs = array();
				foreach($config as $conf)	{
					$configs[$conf->configname] =  $conf->configvalue;	
								
				}
				
		return $configs;
	}
	function & makeDefaultCurrency($id,$defaultvalue) {

		if (is_numeric($id) == false) return false;
		if (is_numeric($defaultvalue) == false) return false;
		$db = &$this->getDBO();
		$query = "update ".$db->nameQuote('#__wrecruit_currencies')." as currency SET currency.default = 0 ";
		//echo $query;
		$db->setQuery( $query );
		if (!$db->query()) {
			return false;
		}
		$row  = &$this->getTable('currency');
		$row->id = $id;
		$row->default = $defaultvalue;
		if (!$row->store()) {
			$this->setError($this->_db->getErrorMsg());
			return false;
		}
		return true;
	}


	function getExtension($str) {
		 $i = strrpos($str,".");
		 if (!$i) { return ""; }
		 $l = strlen($str) - $i;
		 $ext = substr($str,$i+1,$l);
		 return $ext;
	}

}
?>
